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

View File

@ -1,13 +1,59 @@
package com.totopia.server.auth.payload;
import lombok.Data;
@Data
public class JwtSigninResponse {
private String accessToken;
private String tokenType = "Bearer";
public JwtSigninResponse(String accessToken) {
this.accessToken = accessToken;
}
}
package com.totopia.server.auth.payload;
public class JwtSigninResponse {
private String accessToken;
private String tokenType = "Bearer";
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;
import javax.validation.constraints.NotBlank;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class SigninRequest {
@NotBlank
private String username;
@NotBlank
private String password;
}
package com.totopia.server.auth.payload;
import javax.validation.constraints.NotBlank;
public class SigninRequest {
@NotBlank
private String username;
@NotBlank
private String password;
public SigninRequest(@NotBlank String username, @NotBlank String password) {
this.username = username;
this.password = password;
}
public SigninRequest() {
}
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;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import lombok.Data;
@Data
public class SignupRequest {
@NotBlank
@Size(min = 4, max = 40)
private String name;
@NotBlank
@Size(min = 3, max = 15)
private String username;
@NotBlank
@Size(max = 40)
@Email
private String email;
@NotBlank
@Size(min = 6, max = 20)
private String password;
}
package com.totopia.server.auth.payload;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
public class SignupRequest {
@NotBlank
@Size(min = 4, max = 40)
private String name;
@NotBlank
@Size(min = 3, max = 15)
private String username;
@NotBlank
@Size(max = 40)
@Email
private String email;
@NotBlank
@Size(min = 6, max = 20)
private String password;
public SignupRequest() {
}
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;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.io.Serializable;
import java.util.Date;
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = { "createdAt", "updatedAt" }, allowGetters = true)
@Data
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public abstract class DateAuditEntity implements Serializable {
private static final long serialVersionUID = 3495202400889041952L;
@CreatedDate
@Temporal(TemporalType.TIMESTAMP)
private Date createdAt;
@LastModifiedDate
@Temporal(TemporalType.TIMESTAMP)
private Date updatedAt;
}
package com.totopia.server.commons.data.entity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.experimental.SuperBuilder;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.io.Serializable;
import java.util.Date;
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = { "createdAt", "updatedAt" }, allowGetters = true)
@SuperBuilder
public abstract class DateAuditEntity implements Serializable {
private static final long serialVersionUID = 3495202400889041952L;
@CreatedDate
@Temporal(TemporalType.TIMESTAMP)
private Date createdAt;
@LastModifiedDate
@Temporal(TemporalType.TIMESTAMP)
private Date updatedAt;
public DateAuditEntity(Date createdAt, Date updatedAt) {
this.createdAt = createdAt;
this.updatedAt = updatedAt;
}
public DateAuditEntity() {
}
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;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.LastModifiedBy;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import javax.persistence.MappedSuperclass;
/**
* Created by rajeevkumarsingh on 19/08/17.
*/
@MappedSuperclass
@JsonIgnoreProperties(value = { "createdBy", "updatedBy" }, allowGetters = true)
@SuperBuilder
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public abstract class UserDateAuditEntity extends DateAuditEntity {
private static final long serialVersionUID = 6379346917688414915L;
@CreatedBy
private Long createdBy;
@LastModifiedBy
private Long updatedBy;
}
package com.totopia.server.commons.data.entity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.experimental.SuperBuilder;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.LastModifiedBy;
import javax.persistence.MappedSuperclass;
/**
* Created by rajeevkumarsingh on 19/08/17.
*/
@MappedSuperclass
@JsonIgnoreProperties(value = { "createdBy", "updatedBy" }, allowGetters = true)
@SuperBuilder
public abstract class UserDateAuditEntity extends DateAuditEntity {
private static final long serialVersionUID = 6379346917688414915L;
@CreatedBy
private Long createdBy;
@LastModifiedBy
private Long updatedBy;
public UserDateAuditEntity(Long createdBy, Long updatedBy) {
this.createdBy = createdBy;
this.updatedBy = updatedBy;
}
public UserDateAuditEntity() {
}
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;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class ApiResponse {
private Boolean success;
private String message;
}
package com.totopia.server.commons.data.payload;
public class ApiResponse {
private Boolean success;
private String message;
public ApiResponse(Boolean success, String message) {
this.success = success;
this.message = message;
}
public ApiResponse() {
}
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;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.Optional;
import com.totopia.server.config.security.SecurityUserDetails;
@Configuration
@EnableJpaAuditing
public class AuditingConfig {
@Bean
public AuditorAware<Long> auditorProvider() {
return new SpringSecurityAuditAwareImpl();
}
}
class SpringSecurityAuditAwareImpl implements AuditorAware<Long> {
@Override
public Optional<Long> getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || !authentication.isAuthenticated()
|| authentication instanceof AnonymousAuthenticationToken) {
return Optional.empty();
}
SecurityUserDetails securityUserDetails = (SecurityUserDetails) authentication.getPrincipal();
return Optional.ofNullable(securityUserDetails.getId());
}
}
package com.totopia.server.config;
import com.totopia.server.config.security.SecurityUserDetails;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.Optional;
@Configuration
@EnableJpaAuditing
public class AuditingConfig {
@Bean
public AuditorAware<Long> auditorProvider() {
return new SpringSecurityAuditAwareImpl();
}
}
class SpringSecurityAuditAwareImpl implements AuditorAware<Long> {
@Override
public Optional<Long> getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || !authentication.isAuthenticated()
|| authentication instanceof AnonymousAuthenticationToken) {
return Optional.empty();
}
SecurityUserDetails securityUserDetails = (SecurityUserDetails) authentication.getPrincipal();
return Optional.ofNullable(securityUserDetails.getId());
}
}

View File

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

View File

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

View File

@ -1,66 +1,63 @@
package com.totopia.server.config.jwt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.totopia.server.config.security.SecurityUserDetailsService;
import java.io.IOException;
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Autowired
private JwtTokenProvider tokenProvider;
@Autowired
private SecurityUserDetailsService securityUserDetailsService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
try {
String jwt = getJwtFromRequest(request);
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.
*/
UserDetails userDetails = securityUserDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null,
userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
} catch (Exception ex) {
log.error("Could not set user authentication in security context", ex);
}
filterChain.doFilter(request, response);
}
private String getJwtFromRequest(HttpServletRequest request) {
String bearerToken = request.getHeader("Authorization");
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7, bearerToken.length());
}
return null;
}
}
package com.totopia.server.config.jwt;
import com.totopia.server.config.security.SecurityUserDetailsService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private static final Logger log = org.slf4j.LoggerFactory.getLogger(JwtAuthenticationFilter.class);
@Autowired
private JwtTokenProvider tokenProvider;
@Autowired
private SecurityUserDetailsService securityUserDetailsService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
try {
String jwt = getJwtFromRequest(request);
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.
*/
UserDetails userDetails = securityUserDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null,
userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
} catch (Exception ex) {
log.error("Could not set user authentication in security context", ex);
}
filterChain.doFilter(request, response);
}
private String getJwtFromRequest(HttpServletRequest request) {
String bearerToken = request.getHeader("Authorization");
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7, bearerToken.length());
}
return null;
}
}

View File

@ -1,73 +1,65 @@
package com.totopia.server.config.jwt;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
import lombok.extern.slf4j.Slf4j;
import java.util.Date;
import java.util.stream.Collectors;
import com.totopia.server.config.security.SecurityUserDetails;
/**
* Created by rajeevkumarsingh on 19/08/17.
*/
@Component
@Slf4j
public class JwtTokenProvider {
private static final String AUTHORITIES_KEY = "authorities";
@Value("${app.jwt.secret}")
private String jwtSecret;
@Value("${app.jwt.expiration}")
private int jwtExpirationInMs;
public String generateToken(Authentication authentication) {
SecurityUserDetails userPrincipal = (SecurityUserDetails) authentication.getPrincipal();
Date now = new Date();
Date expiryDate = new Date(now.getTime() + jwtExpirationInMs);
final String authorities = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority)
.collect(Collectors.joining(","));
return Jwts.builder().setSubject(userPrincipal.getUsername()).claim(AUTHORITIES_KEY, authorities)
.setIssuedAt(new Date()).setExpiration(expiryDate).signWith(SignatureAlgorithm.HS512, jwtSecret).compact();
}
public String getUsernameFromJWT(String token) {
Claims claims = Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody();
return claims.getSubject();
}
public boolean validateToken(String authToken) {
try {
Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken);
return true;
} catch (SignatureException ex) {
log.error("Invalid JWT signature");
} catch (MalformedJwtException ex) {
log.error("Invalid JWT token");
} 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;
}
}
package com.totopia.server.config.jwt;
import com.totopia.server.config.security.SecurityUserDetails;
import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.stream.Collectors;
/**
* Created by rajeevkumarsingh on 19/08/17.
*/
@Component
public class JwtTokenProvider {
private static final String AUTHORITIES_KEY = "authorities";
private static final Logger log = org.slf4j.LoggerFactory.getLogger(JwtTokenProvider.class);
@Value("${app.jwt.secret}")
private String jwtSecret;
@Value("${app.jwt.expiration}")
private int jwtExpirationInMs;
public String generateToken(Authentication authentication) {
SecurityUserDetails userPrincipal = (SecurityUserDetails) authentication.getPrincipal();
Date now = new Date();
Date expiryDate = new Date(now.getTime() + jwtExpirationInMs);
final String authorities = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority)
.collect(Collectors.joining(","));
return Jwts.builder().setSubject(userPrincipal.getUsername()).claim(AUTHORITIES_KEY, authorities)
.setIssuedAt(new Date()).setExpiration(expiryDate).signWith(SignatureAlgorithm.HS512, jwtSecret).compact();
}
public String getUsernameFromJWT(String token) {
Claims claims = Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody();
return claims.getSubject();
}
public boolean validateToken(String authToken) {
try {
Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken);
return true;
} catch (SignatureException ex) {
log.error("Invalid JWT signature");
} catch (MalformedJwtException ex) {
log.error("Invalid JWT token");
} 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;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.totopia.server.modules.user.entity.UserEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class SecurityUserDetails implements UserDetails {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private String username;
@JsonIgnore
private String email;
@JsonIgnore
private String password;
private Collection<? extends GrantedAuthority> authorities;
@Override
public String getUsername() {
return username;
}
@Override
public String getPassword() {
return password;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
SecurityUserDetails that = (SecurityUserDetails) o;
return Objects.equals(id, that.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
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();
}
}
package com.totopia.server.config.security;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.totopia.server.modules.user.entity.UserEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class SecurityUserDetails implements UserDetails {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private String username;
@JsonIgnore
private String email;
@JsonIgnore
private String password;
private Collection<? extends GrantedAuthority> authorities;
public SecurityUserDetails(Long id, String name, String username, String email, String password, Collection<? extends GrantedAuthority> authorities) {
this.id = id;
this.name = name;
this.username = username;
this.email = email;
this.password = password;
this.authorities = authorities;
}
public SecurityUserDetails() {
}
public static SecurityUserDetailsBuilder builder() {
return new SecurityUserDetailsBuilder();
}
@Override
public String getUsername() {
return username;
}
@Override
public String getPassword() {
return password;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
SecurityUserDetails that = (SecurityUserDetails) o;
return Objects.equals(id, that.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
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;
import com.totopia.server.commons.exception.ResourceNotFoundException;
import com.totopia.server.modules.user.entity.UserEntity;
import com.totopia.server.modules.user.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class SecurityUserDetailsService implements UserDetailsService {
@Autowired
UserRepository userRepository;
@Override
@Transactional
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// Let people login with either username or email
UserEntity user = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User not found with username : " + username));
return SecurityUserDetails.create(user);
}
@Transactional
public UserDetails loadUserById(Long id) {
UserEntity user = userRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("User", "id", id));
return SecurityUserDetails.create(user);
}
}
package com.totopia.server.config.security;
import com.totopia.server.commons.exception.ResourceNotFoundException;
import com.totopia.server.modules.user.entity.UserEntity;
import com.totopia.server.modules.user.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class SecurityUserDetailsService implements UserDetailsService {
@Autowired
UserRepository userRepository;
@Override
@Transactional
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// Let people login with either username or email
UserEntity user = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User not found with username : " + username));
return SecurityUserDetails.create(user);
}
@Transactional
public UserDetails loadUserById(Long id) {
UserEntity user = userRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("User", "id", id));
return SecurityUserDetails.create(user);
}
}

View File

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

View File

@ -1,111 +1,102 @@
package com.totopia.server.modules.dashboard.controller;
import java.util.List;
import javax.transaction.Transactional;
import com.totopia.server.commons.exception.ResourceNotFoundException;
import com.totopia.server.modules.dashboard.entity.DashboardEntity;
import com.totopia.server.modules.dashboard.repository.DashboardRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DashboardController {
@Autowired
private DashboardRepository dashboardRepository;
@PostMapping(value = "/dashboards")
@ResponseStatus(code = HttpStatus.CREATED)
public DashboardEntity save(@RequestBody DashboardEntity dashboard) {
return dashboardRepository.save(dashboard);
}
@PreAuthorize("hasAnyRole('ROLE_USER', 'ROLE_ADMIN', 'ROLE_SUPER_ADMIN')")
@GetMapping(value = "/dashboards")
public List<DashboardEntity> all() {
return dashboardRepository.findByOrderBySortOrder();
}
@GetMapping(value = "/dashboards/{id}")
public DashboardEntity findById(@PathVariable Integer id) {
return dashboardRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Dashboard", "id", id));
}
@DeleteMapping(value = "/dashboards/{id}")
@Transactional
public ResponseEntity<?> deleteDashboard(@PathVariable Integer id) {
return dashboardRepository.findById(id).map(dashboard -> {
dashboardRepository.decreaseSortOrder(dashboard.getSortOrder(), (int) dashboardRepository.count());
dashboardRepository.delete(dashboard);
return ResponseEntity.ok().build();
}).orElseThrow(() -> new ResourceNotFoundException("Dashboard", "id", id));
}
@PutMapping(value = "/dashboards/{id}")
public ResponseEntity<DashboardEntity> updateDashboard(@PathVariable Integer id,
@RequestBody DashboardEntity newDashboard) {
return dashboardRepository.findById(id).map(dashboard -> {
dashboardRepository.save(dashboard);
return ResponseEntity.ok(dashboard);
}).orElseThrow(() -> new ResourceNotFoundException("Dashboard", "id", id));
}
@PutMapping(value = "/dashboards/{id}/display/{display}")
public ResponseEntity<DashboardEntity> updateDashboardDisplay(@PathVariable Integer id,
@PathVariable Boolean display) {
return dashboardRepository.findById(id).map(dashboard -> {
dashboard.setDisplay(display);
dashboardRepository.save(dashboard);
return ResponseEntity.ok(dashboard);
}).orElseThrow(() -> new ResourceNotFoundException("Dashboard", "id", id));
}
@PutMapping(value = "/dashboards/{id}/sort_order/{targetSortOrder}")
@Transactional
public ResponseEntity<DashboardEntity> updateDashboardSortOrder(@PathVariable Integer id,
@PathVariable Integer targetSortOrder) {
return dashboardRepository.findById(id).map(dashboard -> {
if (targetSortOrder.equals(dashboard.getSortOrder())) {
return ResponseEntity.ok(dashboard);
}
if (0 > targetSortOrder || dashboardRepository.count() < targetSortOrder) {
return ResponseEntity.ok(dashboard);
}
Integer sourceSortOrder = dashboard.getSortOrder();
if (targetSortOrder > sourceSortOrder) {
dashboardRepository.decreaseSortOrder(sourceSortOrder, targetSortOrder);
} else {
dashboardRepository.increaseSortOrder(sourceSortOrder, targetSortOrder);
}
dashboard.setSortOrder(targetSortOrder);
dashboardRepository.save(dashboard);
return ResponseEntity.ok(dashboard);
}).orElseThrow(() -> new ResourceNotFoundException("Dashboard", "id", id));
}
}
package com.totopia.server.modules.dashboard.controller;
import com.totopia.server.commons.exception.ResourceNotFoundException;
import com.totopia.server.modules.dashboard.entity.DashboardEntity;
import com.totopia.server.modules.dashboard.repository.DashboardRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.transaction.Transactional;
import java.util.List;
@RestController
public class DashboardController {
@Autowired
private DashboardRepository dashboardRepository;
@PostMapping(value = "/dashboards")
@ResponseStatus(code = HttpStatus.CREATED)
public DashboardEntity save(@RequestBody DashboardEntity dashboard) {
return dashboardRepository.save(dashboard);
}
@PreAuthorize("hasAnyRole('ROLE_USER', 'ROLE_ADMIN', 'ROLE_SUPER_ADMIN')")
@GetMapping(value = "/dashboards")
public List<DashboardEntity> all() {
return dashboardRepository.findByOrderBySortOrder();
}
@GetMapping(value = "/dashboards/{id}")
public DashboardEntity findById(@PathVariable Integer id) {
return dashboardRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Dashboard", "id", id));
}
@DeleteMapping(value = "/dashboards/{id}")
@Transactional
public ResponseEntity<?> deleteDashboard(@PathVariable Integer id) {
return dashboardRepository.findById(id).map(dashboard -> {
dashboardRepository.decreaseSortOrder(dashboard.getSortOrder(), (int) dashboardRepository.count());
dashboardRepository.delete(dashboard);
return ResponseEntity.ok().build();
}).orElseThrow(() -> new ResourceNotFoundException("Dashboard", "id", id));
}
@PutMapping(value = "/dashboards/{id}")
public ResponseEntity<DashboardEntity> updateDashboard(@PathVariable Integer id,
@RequestBody DashboardEntity newDashboard) {
return dashboardRepository.findById(id).map(dashboard -> {
dashboardRepository.save(dashboard);
return ResponseEntity.ok(dashboard);
}).orElseThrow(() -> new ResourceNotFoundException("Dashboard", "id", id));
}
@PutMapping(value = "/dashboards/{id}/display/{display}")
public ResponseEntity<DashboardEntity> updateDashboardDisplay(@PathVariable Integer id,
@PathVariable Boolean display) {
return dashboardRepository.findById(id).map(dashboard -> {
dashboard.setDisplay(display);
dashboardRepository.save(dashboard);
return ResponseEntity.ok(dashboard);
}).orElseThrow(() -> new ResourceNotFoundException("Dashboard", "id", id));
}
@PutMapping(value = "/dashboards/{id}/sort_order/{targetSortOrder}")
@Transactional
public ResponseEntity<DashboardEntity> updateDashboardSortOrder(@PathVariable Integer id,
@PathVariable Integer targetSortOrder) {
return dashboardRepository.findById(id).map(dashboard -> {
if (targetSortOrder.equals(dashboard.getSortOrder())) {
return ResponseEntity.ok(dashboard);
}
if (0 > targetSortOrder || dashboardRepository.count() < targetSortOrder) {
return ResponseEntity.ok(dashboard);
}
Integer sourceSortOrder = dashboard.getSortOrder();
if (targetSortOrder > sourceSortOrder) {
dashboardRepository.decreaseSortOrder(sourceSortOrder, targetSortOrder);
} 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;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import com.totopia.server.commons.data.entity.UserDateAuditEntity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
@Entity
@Table(name = "dashboard")
@Data
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class DashboardEntity extends UserDateAuditEntity {
private static final long serialVersionUID = 8891163223262220481L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Basic
@Column(name = "title", nullable = false, length = 150)
private String title;
@Basic
@Column(name = "description", nullable = true, length = 500)
private String description;
@Basic
@Column(name = "url", nullable = false, length = 250)
private String url;
@Basic
@Column(name = "sort_order", nullable = false)
private Integer sortOrder;
@Builder.Default
@Basic
@Column(name = "display", nullable = false)
private Boolean display = true;
}
package com.totopia.server.modules.dashboard.entity;
import com.totopia.server.commons.data.entity.UserDateAuditEntity;
import lombok.experimental.SuperBuilder;
import javax.persistence.*;
@Entity
@Table(name = "dashboard")
@SuperBuilder
public class DashboardEntity extends UserDateAuditEntity {
private static final long serialVersionUID = 8891163223262220481L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Basic
@Column(name = "title", nullable = false, length = 150)
private String title;
@Basic
@Column(name = "description", nullable = true, length = 500)
private String description;
@Basic
@Column(name = "url", nullable = false, length = 250)
private String url;
@Basic
@Column(name = "sort_order", nullable = false)
private Integer sortOrder;
@Basic
@Column(name = "display", nullable = false)
private Boolean display = true;
public DashboardEntity(Integer id, String title, String description, String url, Integer sortOrder, Boolean display) {
this.id = id;
this.title = title;
this.description = description;
this.url = url;
this.sortOrder = sortOrder;
this.display = display;
}
public DashboardEntity() {
}
public Integer getId() {
return this.id;
}
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;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
import com.totopia.server.modules.dashboard.entity.DashboardEntity;
public interface DashboardRepository extends JpaRepository<DashboardEntity, Integer> {
List<DashboardEntity> findByOrderBySortOrder();
@Modifying
@Query("update DashboardEntity d set d.sortOrder = d.sortOrder + 1 where d.sortOrder < :sourceSortOrder and d.sortOrder >= :targetSortOrder")
int increaseSortOrder(@Param("sourceSortOrder") Integer sourceSortOrder,
@Param("targetSortOrder") Integer targetSortOrder);
@Modifying
@Query("update DashboardEntity d set d.sortOrder = d.sortOrder - 1 where d.sortOrder > :sourceSortOrder and d.sortOrder <= :targetSortOrder")
int decreaseSortOrder(@Param("sourceSortOrder") Integer sourceSortOrder,
@Param("targetSortOrder") Integer targetSortOrder);
}
package com.totopia.server.modules.dashboard.repository;
import com.totopia.server.modules.dashboard.entity.DashboardEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface DashboardRepository extends JpaRepository<DashboardEntity, Integer> {
List<DashboardEntity> findByOrderBySortOrder();
@Modifying
@Query("update DashboardEntity d set d.sortOrder = d.sortOrder + 1 where d.sortOrder < :sourceSortOrder and d.sortOrder >= :targetSortOrder")
int increaseSortOrder(@Param("sourceSortOrder") Integer sourceSortOrder,
@Param("targetSortOrder") Integer targetSortOrder);
@Modifying
@Query("update DashboardEntity d set d.sortOrder = d.sortOrder - 1 where d.sortOrder > :sourceSortOrder and d.sortOrder <= :targetSortOrder")
int decreaseSortOrder(@Param("sourceSortOrder") Integer sourceSortOrder,
@Param("targetSortOrder") Integer targetSortOrder);
}

View File

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

View File

@ -1,26 +1,12 @@
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 lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import javax.persistence.*;
@Entity(name = "bank_account")
@Data
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class BankAccountEntity extends UserDateAuditEntity {
private static final long serialVersionUID = -8628291684559836128L;
@ -46,4 +32,101 @@ public class BankAccountEntity extends UserDateAuditEntity {
@Column(name = "username", nullable = false)
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;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import com.totopia.server.modules.user.type.RoleName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity(name = "roles")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class RoleEntity implements Serializable {
private static final long serialVersionUID = 5100719044067326295L;
@Id
@GeneratedValue(generator = "role_generator")
@SequenceGenerator(name = "role_generator", sequenceName = "role_sequence", initialValue = 1)
private Short id;
@Enumerated(EnumType.STRING)
@Column(name = "name", length = 60)
private RoleName name;
}
package com.totopia.server.modules.user.entity;
import com.totopia.server.modules.user.type.RoleName;
import javax.persistence.*;
import java.io.Serializable;
@Entity(name = "roles")
public class RoleEntity implements Serializable {
private static final long serialVersionUID = 5100719044067326295L;
@Id
@GeneratedValue(generator = "role_generator")
@SequenceGenerator(name = "role_generator", sequenceName = "role_sequence", initialValue = 1)
private Short id;
@Enumerated(EnumType.STRING)
@Column(name = "name", length = 60)
private RoleName name;
public RoleEntity(Short id, RoleName name) {
this.id = id;
this.name = name;
}
public RoleEntity() {
}
public static RoleEntityBuilder builder() {
return new RoleEntityBuilder();
}
public Short getId() {
return this.id;
}
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;
import java.util.Date;
import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.totopia.server.commons.data.entity.DateAuditEntity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.Builder.Default;
import lombok.experimental.SuperBuilder;
@Entity
@Table(name = "users", uniqueConstraints = { @UniqueConstraint(columnNames = { "username" }),
@UniqueConstraint(columnNames = { "email" }) })
@Data
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class UserEntity extends DateAuditEntity {
private static final long serialVersionUID = 8891163223262220481L;
@Id
@Column(name = "username", unique = true, nullable = false, length = 150)
private String username;
@Basic
@Column(name = "password", nullable = false, length = 100)
@JsonIgnore
private String password;
@Basic
@Column(name = "nickname", nullable = false, length = 150)
private String nickname;
@Basic
@Column(name = "email", nullable = false, length = 100)
private String email;
@Basic
@Column(name = "block", nullable = false)
@Default
private Boolean block = false;
@Basic
@Column(name = "send_email", nullable = false)
@Default
private Boolean sendEmail = true;
@Basic
@Column(name = "activation", nullable = true, length = 100)
private String activation;
@Basic
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "last_reset_time", nullable = true)
private Date lastResetTime;
@Basic
@Column(name = "reset_count", nullable = false)
@Default
private Long resetCount = 0L;
@Basic
@Column(name = "otp_key", nullable = true, length = 1000)
private String otpKey;
@Basic
@Column(name = "otep", nullable = true, length = 1000)
private String otep;
@Basic
@Column(name = "require_reset", nullable = true)
@Default
private Boolean requireReset = false;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<RoleEntity> roles;
}
// 아이디
// 로그인 아이디
// 로그인 패스워드
// 로그인 패스워드 문자
// 이메일
// 닉네임
// 은행명
// 계좌번호
// 예금주
// 추천인
// 추천수
// 게시판 제한 여부
// 쿠폰
// 충전방식
// 비고
// 종목별 베팅제한
// 상태표기
// 휴대폰번호
// 추천권한 여부
// 가입상태
// 소속
// 레벨
// 보유머니
// 포인트
// 회원상태
// 룰렛개수
// 계좌순번
// 가입날짜
// 최근접속 날짜
// 가입 아이피
// 최근 접속 아이피
// 베팅 알림
// API 연결
package com.totopia.server.modules.user.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.totopia.server.commons.data.entity.DateAuditEntity;
import lombok.experimental.SuperBuilder;
import javax.persistence.*;
import java.util.Date;
import java.util.Set;
@Entity
@Table(name = "users", uniqueConstraints = { @UniqueConstraint(columnNames = { "username" }),
@UniqueConstraint(columnNames = { "email" }) })
@SuperBuilder
public class UserEntity extends DateAuditEntity {
private static final long serialVersionUID = 8891163223262220481L;
@Id
@Column(name = "username", unique = true, nullable = false, length = 150)
private String username;
@Basic
@Column(name = "password", nullable = false, length = 100)
@JsonIgnore
private String password;
@Basic
@Column(name = "nickname", nullable = false, length = 150)
private String nickname;
@Basic
@Column(name = "email", nullable = false, length = 100)
private String email;
@Basic
@Column(name = "block", nullable = false)
private Boolean block = false;
@Basic
@Column(name = "send_email", nullable = false)
private Boolean sendEmail = true;
@Basic
@Column(name = "activation", nullable = true, length = 100)
private String activation;
@Basic
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "last_reset_time", nullable = true)
private Date lastResetTime;
@Basic
@Column(name = "reset_count", nullable = false)
private Long resetCount = 0L;
@Basic
@Column(name = "otp_key", nullable = true, length = 1000)
private String otpKey;
@Basic
@Column(name = "otep", nullable = true, length = 1000)
private String otep;
@Basic
@Column(name = "require_reset", nullable = true)
private Boolean requireReset = false;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<RoleEntity> roles;
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) {
this.username = username;
this.password = password;
this.nickname = nickname;
this.email = email;
this.block = block;
this.sendEmail = sendEmail;
this.activation = activation;
this.lastResetTime = lastResetTime;
this.resetCount = resetCount;
this.otpKey = otpKey;
this.otep = otep;
this.requireReset = requireReset;
this.roles = roles;
}
public UserEntity() {
}
public String getUsername() {
return this.username;
}
public String getPassword() {
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;
}
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;
import org.springframework.data.jpa.repository.JpaRepository;
import com.totopia.server.modules.user.entity.BankAccountEntity;
public interface BankAccountRepository extends JpaRepository<BankAccountEntity, Long> {
}
package com.totopia.server.modules.user.repository;
import com.totopia.server.modules.user.entity.BankAccountEntity;
import org.springframework.data.jpa.repository.JpaRepository;
public interface BankAccountRepository extends JpaRepository<BankAccountEntity, Long> {
}

View File

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

View File

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

View File

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

View File

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