Skip to content

Commit

Permalink
feat: oauth route
Browse files Browse the repository at this point in the history
Signed-off-by: MatheusVict <matheusvictorhenrique@gmail.com>
  • Loading branch information
MatheusVict committed Dec 1, 2023
1 parent 5765b62 commit a0a0fc6
Show file tree
Hide file tree
Showing 7 changed files with 100 additions and 1 deletion.
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.32.1</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Excepti
.requestMatchers(HttpMethod.POST, "/api/v1/auth/login").permitAll()
.requestMatchers(HttpMethod.POST, "/api/v1/auth/register").permitAll()
.requestMatchers(HttpMethod.GET, "/api/v1/posts").permitAll()
.requestMatchers(HttpMethod.POST, "/api/v1/auth/login/google").permitAll()
.anyRequest().authenticated()
)
.addFilterBefore(securityFilter, UsernamePasswordAuthenticationFilter.class)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.pet.foundation.pataamiga.controller.responses.LoginResponse;
import com.pet.foundation.pataamiga.controller.responses.RegisterResponse;
import com.pet.foundation.pataamiga.domain.user.dto.LoginDTO;
import com.pet.foundation.pataamiga.domain.user.dto.LoginGoogleDTO;
import com.pet.foundation.pataamiga.domain.user.dto.UserCreateDTO;
import com.pet.foundation.pataamiga.service.AuthService;
import com.pet.foundation.pataamiga.swagger.annotatios.ConflictResponse;
Expand Down Expand Up @@ -35,6 +36,15 @@ public ResponseEntity<LoginResponse> login(@RequestBody @Valid LoginDTO loginDTO
return ResponseEntity.ok(authService.login(loginDTO));
}

@PostMapping("/login/google")
@Operation(summary = "Login with Google", description = "You can login with your Google account")
@Tag(name = "auth")
@OkResponse
@ForbiddenResponse
public ResponseEntity<LoginResponse> loginWithGoogle(@RequestBody LoginGoogleDTO loginInfo) throws Exception {
return ResponseEntity.ok(authService.loginWithGoogle(loginInfo.token()));
}


@PostMapping("/register")
@Operation(summary = "Register", description = "You can register with your name, email and password")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package com.pet.foundation.pataamiga.domain.user.dto;

public record LoginGoogleDTO(
String token
) {
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
import com.pet.foundation.pataamiga.domain.user.User;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import lombok.Builder;

@Builder
public record UserCreateDTO(
@NotBlank(message = "Name is mandatory")
@Schema(description = "User name", example = "John Doe")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,13 @@
import com.pet.foundation.pataamiga.domain.user.dto.LoginDTO;
import com.pet.foundation.pataamiga.domain.user.dto.UserCreateDTO;

import java.io.IOException;
import java.security.GeneralSecurityException;

public interface AuthService {
LoginResponse login(LoginDTO loginDTO);

LoginResponse loginWithGoogle(String token) throws Exception;

RegisterResponse register(UserCreateDTO userCreateDTO);
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
package com.pet.foundation.pataamiga.service.impl;

import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.pet.foundation.pataamiga.controller.responses.LoginResponse;
import com.pet.foundation.pataamiga.controller.responses.RegisterResponse;
import com.pet.foundation.pataamiga.domain.user.User;
Expand All @@ -9,13 +14,22 @@
import com.pet.foundation.pataamiga.service.TokenService;
import com.pet.foundation.pataamiga.service.UserService;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.List;
import java.util.UUID;

@Service
@AllArgsConstructor
@RequiredArgsConstructor
@Log4j2
public class AuthServiceImpl implements AuthService {

private final UserService userService;
Expand All @@ -24,6 +38,9 @@ public class AuthServiceImpl implements AuthService {

private final TokenService tokenService;

@Value("${google.client.id}")
private String GOOGLE_CLIENT_ID;

@Override
public LoginResponse login(LoginDTO loginDTO) {
UsernamePasswordAuthenticationToken userNamePassword =
Expand All @@ -34,9 +51,62 @@ public LoginResponse login(LoginDTO loginDTO) {
return new LoginResponse(token);
}

@Override
public LoginResponse loginWithGoogle(String token) throws Exception {

log.info("token: {}", token);
GoogleIdTokenVerifier verifier = buildGoogleIdTokenVerifier();

log.info("verifier: {}", verifier);

GoogleIdToken idToken = verifier.verify(token);
log.info("idToken: {}", idToken);

if (idToken != null) {
Payload payload = idToken.getPayload();
String email = payload.getEmail();
String name = (String) payload.get("name");
String picture = (String) payload.get("picture");

User user = userService.getUserByEmail(email);

log.info("user: {}", user);

if (user == null) {
UserCreateDTO userCreateDTO = buildUserCreateDTO(email, name, picture);
String userCreatedUuid = userService.createUser(userCreateDTO);
user = userService.getUserByUuid(userCreatedUuid);
String tokenGenerated = tokenService.generateToken(user);
return new LoginResponse(tokenGenerated);
}

String tokenGenerated = tokenService.generateToken(user);
return new LoginResponse(tokenGenerated);

} else {
throw new Exception("Invalid ID token");
}
}

@Override
public RegisterResponse register(UserCreateDTO userCreateDTO) {
String userCreatedUuid = userService.createUser(userCreateDTO);
return new RegisterResponse(userCreatedUuid);
}

private GoogleIdTokenVerifier buildGoogleIdTokenVerifier() {
return new GoogleIdTokenVerifier.Builder(new NetHttpTransport(), new GsonFactory())
.setAudience(List.of(GOOGLE_CLIENT_ID))
.build();
}

private UserCreateDTO buildUserCreateDTO(String email, String name, String picture) {
return UserCreateDTO.builder()
.email(email)
.name(name)
.profilePicture(picture)
.password(UUID.randomUUID().toString())
.phone("9 9999-9999")
.build();
}
}

0 comments on commit a0a0fc6

Please sign in to comment.