Skip to content

Commit

Permalink
Merge pull request #186 from Kernel360/develop
Browse files Browse the repository at this point in the history
merge
  • Loading branch information
xorwns118 authored Aug 28, 2024
2 parents 82541ea + 22f1d09 commit 9eda7d6
Show file tree
Hide file tree
Showing 116 changed files with 2,553 additions and 1,004 deletions.
8 changes: 5 additions & 3 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,9 @@ javadoc {
bootJar{
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
tasks.withType(Test) {
// Skip tests
enabled = false

test {
useJUnitPlatform()
include '**/*Test.class'
include '**/*Tests.class'
}
16 changes: 3 additions & 13 deletions src/main/java/com/speech/up/api/converter/WavToRaw.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,16 @@
import javax.sound.sampled.*;
import java.io.*;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import jakarta.validation.constraints.NotNull;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Getter
public class WavToRaw {

private static final Logger log = LoggerFactory.getLogger(WavToRaw.class);
private static final AudioFormat FORMAT = new AudioFormat(16000, 16, 1, true, false);
private static final int HEADER_SIZE = 44; // WAV 파일 헤더 크기

Expand All @@ -28,15 +27,7 @@ public byte[] convertToRawPcm(MultipartFile multipartFile) throws UnsupportedAud
multipartFile.transferTo(file);
try (AudioInputStream sourceStream = AudioSystem.getAudioInputStream(file)) {
AudioFormat sourceFormat = sourceStream.getFormat();
AudioFormat targetFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
16000,
16,
1,
2,
16000,
false
);
AudioFormat targetFormat = FORMAT;

if (!AudioSystem.isConversionSupported(targetFormat, sourceFormat)) {
throw new UnsupportedAudioFileException("The source format is not supported.");
Expand All @@ -51,7 +42,6 @@ public byte[] convertToRawPcm(MultipartFile multipartFile) throws UnsupportedAud
byteArrayOutputStream.write(buffer, 0, bytesRead);
}

// WAV 헤더를 제거하고 PCM 데이터만 반환
byte[] rawPcmData = byteArrayOutputStream.toByteArray();
return formatWav2Raw(rawPcmData);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@
import java.nio.charset.StandardCharsets;
import java.util.Base64;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
Expand All @@ -30,13 +28,13 @@
import com.speech.up.record.repository.RecordRepository;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@RequiredArgsConstructor
public class VoiceToTextService {

private static final Logger log = LoggerFactory.getLogger(VoiceToTextService.class);

@Value("${api.voice.accessKey}")
private String accessKey;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public WebSecurityCustomizer configured() { // 스프링 시큐리티 기능 비
.requestMatchers(
new AntPathRequestMatcher("/images/**"),
new AntPathRequestMatcher("/css/**"),
new AntPathRequestMatcher("/scriptPage/js/**"),
new AntPathRequestMatcher("/js/**"),
new AntPathRequestMatcher("/map")
);
}
Expand All @@ -66,7 +66,7 @@ protected SecurityFilterChain configure(HttpSecurity httpSecurity) throws Except
"api/v1/auth/**", "/oauth2/**", "/sign-up", "/logout", "/login",
"/boards", "/boards/**", "/api/upload",
"/.well-known/**", "/api/open/data/*",
"/report", "/scripts", "/script-write", "/script-list", "/replies/**",
"/report", "/scripts", "/script-write", "/scripts-list", "/replies/**",
"/admin/view", "/page/me", "/speech-record", "reports/**", "/").permitAll()
.requestMatchers("/api/boards").hasAnyRole("ADMIN_USER", "GENERAL_USER")
.requestMatchers("/users/me").hasAnyRole("ADMIN_USER", "GENERAL_USER")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
Expand Down Expand Up @@ -46,17 +47,18 @@ protected void doFilterInternal(@Nullable HttpServletRequest request, @Nullable
filterChain.doFilter(request, response);
return;
}
String userId = jwtProvider.validate(token);
if(userId == null){
String socialId = jwtProvider.validate(token);
if(socialId == null){
filterChain.doFilter(request, response);
return;
}
UserEntity userEntity = userRepository.findBySocialId(userId);
UserEntity userEntity = userRepository.findBySocialId(socialId)
.orElseThrow(() -> new NoSuchElementException("not found UserEntity by socialId : " + socialId));;
String role = userEntity.getAuthorization();
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(role));
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
AbstractAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userId, token, authorities);
AbstractAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(socialId, token, authorities);

authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
securityContext.setAuthentication(authenticationToken);
Expand Down
11 changes: 6 additions & 5 deletions src/main/java/com/speech/up/auth/provider/GithubProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,32 @@

import org.springframework.security.oauth2.core.user.OAuth2User;

import com.speech.up.auth.service.implement.UserAuthorizationType;
import com.speech.up.auth.service.servicetype.LevelType;
import com.speech.up.auth.service.servicetype.ProviderType;
import com.speech.up.auth.service.implement.UserAuthorizationType;
import com.speech.up.user.entity.UserEntity;

public class GithubProvider implements ProviderOAuth {
final String socialId;
final String email;
final String name;
final String providerType;
final String authorization ;
final String authorization;
final String level;
final boolean isUse;

public GithubProvider(OAuth2User user) {
this.socialId = user.getAttributes().get("id")+"";
this.name = user.getAttributes().get("name")+"";
this.socialId = user.getAttributes().get("id") + "";
this.name = user.getAttributes().get("name") + "";
this.email = "none";
this.providerType = ProviderType.GITHUB.name();
this.authorization = UserAuthorizationType.ROLE_GENERAL_USER.name();
this.level = LevelType.BRONZE.name();
this.isUse = true;
}

@Override
public UserEntity getUser() {
return new UserEntity(socialId, email, level, name, authorization, providerType);
return UserEntity.providerOf(socialId, email, level, name, authorization, providerType);
}
}
14 changes: 7 additions & 7 deletions src/main/java/com/speech/up/auth/provider/GoogleProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,32 @@

import org.springframework.security.oauth2.core.user.OAuth2User;

import com.speech.up.auth.service.implement.UserAuthorizationType;
import com.speech.up.auth.service.servicetype.LevelType;
import com.speech.up.auth.service.servicetype.ProviderType;
import com.speech.up.auth.service.implement.UserAuthorizationType;
import com.speech.up.user.entity.UserEntity;

public class GoogleProvider implements ProviderOAuth {
final String socialId;
final String email;
final String name;
final String providerType;
final String authorization ;
final String authorization;
final String level;
final boolean isUse;


public GoogleProvider(OAuth2User user) {
this.socialId = user.getAttributes().get("sub")+"";
this.socialId = user.getAttributes().get("sub") + "";
this.providerType = ProviderType.GOOGLE.name();
this.email = user.getAttributes().get("email")+"";
this.name = user.getAttributes().get("name")+"";
this.email = user.getAttributes().get("email") + "";
this.name = user.getAttributes().get("name") + "";
this.authorization = UserAuthorizationType.ROLE_GENERAL_USER.name();
this.level = LevelType.BRONZE.name();
this.isUse = true;
}

@Override
public UserEntity getUser() {
return new UserEntity(socialId, email, level, name, authorization, providerType);
return UserEntity.providerOf(socialId, email, level, name, authorization, providerType);
}
}
19 changes: 14 additions & 5 deletions src/main/java/com/speech/up/auth/provider/JwtProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,39 +12,48 @@
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import jakarta.servlet.http.HttpServletRequest;

@Component
public class JwtProvider {
@Value("${jwt.secret.key}")
private String secretKey;

public String createToken(String userId) {
Date expirationDate = Date.from(Instant.now().plus(1, ChronoUnit.HOURS)); // 현재부터 1시간 뒤까지
Key key = Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8)); // 발급받은 토큰 UTF-8 로 인코딩
Date expirationDate = Date.from(Instant.now().plus(1, ChronoUnit.HOURS));
Key key = Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));

return Jwts.builder()
.signWith(key, SignatureAlgorithm.HS256)
.setSubject(userId).setIssuedAt(new Date()).setExpiration(expirationDate).compact();
}

public String validate(String jwt) {
String subject = null;
String subject;
Key key = Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));

try {

subject = Jwts.parserBuilder()
.setSigningKey(key)
.build()
.parseClaimsJws(jwt)
.getBody()
.getSubject();

} catch (NullPointerException nullPointerException) {
throw new IllegalArgumentException("JwtProvider 클래스에 문제 있으니 확인해라.");
} catch (Exception exception) {
throw new IllegalArgumentException(exception);
}
return subject;
}

public String getHeader(HttpServletRequest request) {
String authorization = request.getHeader("Authorization");

if (authorization != null && authorization.startsWith("Bearer ")) {
authorization = authorization.substring(7);
}

return validate(authorization);
}
}
14 changes: 7 additions & 7 deletions src/main/java/com/speech/up/auth/provider/KakaoProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,28 @@

import org.springframework.security.oauth2.core.user.OAuth2User;

import com.speech.up.auth.service.implement.UserAuthorizationType;
import com.speech.up.auth.service.servicetype.LevelType;
import com.speech.up.auth.service.servicetype.ProviderType;
import com.speech.up.auth.service.implement.UserAuthorizationType;
import com.speech.up.user.entity.UserEntity;

public class KakaoProvider implements ProviderOAuth {
final String socialId;
final String email;
final String name;
final String providerType;
final String authorization ;
final String authorization;
final String level;
final boolean isUse;

public KakaoProvider(OAuth2User user) {
Object properties = user.getAttributes().get("properties");
Map<String, String> responseMap = new HashMap<>();
if(properties instanceof Map<?, ?> tempMap) {
if (properties instanceof Map<?, ?> tempMap) {
response(responseMap, tempMap);
}

this.socialId = user.getAttributes().get("id")+"";
this.socialId = user.getAttributes().get("id") + "";
this.providerType = ProviderType.KAKAO.name();
this.email = "none";
this.name = responseMap.get("nickname");
Expand All @@ -35,17 +35,17 @@ public KakaoProvider(OAuth2User user) {
this.isUse = true;
}

private void response(Map<String, String> response, Map<?, ?> tempMap){
private void response(Map<String, String> response, Map<?, ?> tempMap) {
for (Map.Entry<?, ?> entry : tempMap.entrySet()) {
if (entry.getKey() instanceof String && entry.getValue() instanceof String) {
response.put((String) entry.getKey(), (String)entry.getValue());
response.put((String)entry.getKey(), (String)entry.getValue());
}
}
}

@Override
public UserEntity getUser() {
return new UserEntity(socialId, email, level, name, authorization, providerType);
return UserEntity.providerOf(socialId, email, level, name, authorization, providerType);
}

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.speech.up.auth.service.implement;

import java.util.NoSuchElementException;

import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
Expand All @@ -21,7 +23,6 @@
public class OAuth2UserServiceImplement extends DefaultOAuth2UserService {
private final UserRepository userRepository;

@SuppressWarnings("null")
@Override
public OAuth2User loadUser(OAuth2UserRequest request) throws OAuth2AuthenticationException {
OAuth2User oAuth2User = super.loadUser(request);
Expand All @@ -32,11 +33,13 @@ public OAuth2User loadUser(OAuth2UserRequest request) throws OAuth2Authenticatio

assert userEntity != null;

if(!userRepository.existsBySocialId(userEntity.getSocialId())) {
if (!userRepository.existsBySocialId(userEntity.getSocialId())) {
userRepository.save(userEntity);
}else{
UserEntity user = userRepository.findBySocialId(userEntity.getSocialId());
UserEntity updateUserAccess = new UserEntity(user);
} else {
UserEntity user = userRepository.findBySocialId(userEntity.getSocialId())
.orElseThrow(
() -> new NoSuchElementException("not found UserEntity by socialId: " + userEntity.getSocialId()));
UserEntity updateUserAccess = UserEntity.updateUserAccess(user);
userRepository.save(updateUserAccess);
}
return new CustomOAuth2User(userEntity.getSocialId());
Expand Down
Loading

0 comments on commit 9eda7d6

Please sign in to comment.