Skip to content

Commit

Permalink
Merge pull request #4 from PET-foundation/developer
Browse files Browse the repository at this point in the history
Developer
  • Loading branch information
MatheusVict authored Jun 11, 2024
2 parents 86af5c5 + a0a0fc6 commit f86955f
Show file tree
Hide file tree
Showing 46 changed files with 2,179 additions and 32 deletions.
13 changes: 13 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,19 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<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
Expand Up @@ -36,13 +36,14 @@ public ResponseEntity<UserResponseDTO> getUserByUuid(@PathVariable String uuid)
UserResponseDTO response = UserResponseDTO.toResponse(user);
return ResponseEntity.ok(response);
}

@GetMapping("/themselves")
@Operation(summary = "Get user by token")
@Tag(name = "user")
@OkResponse
@ForbiddenResponse
@NotFoundResponse
public ResponseEntity<UserResponseDTO> getUserByToken( @AuthenticationPrincipal UserDetails userDetails) {
public ResponseEntity<UserResponseDTO> getUserByToken(@AuthenticationPrincipal UserDetails userDetails) {
User user = userService.getUserByEmail(userDetails.getUsername());
UserResponseDTO response = UserResponseDTO.toResponse(user);
return ResponseEntity.ok(response);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity(name = "adoptions")
@Entity
@Table(name = "adoptions")
public class Adoption {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;


Expand Down
34 changes: 34 additions & 0 deletions src/main/java/com/pet/foundation/pataamiga/domain/email/Email.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.pet.foundation.pataamiga.domain.email;

import jakarta.persistence.*;
import lombok.Data;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.UUID;

@Entity
@Table(name = "email")
@Data
public class Email implements Serializable {
private static final Long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private UUID uuid;

private String ownerRef;

private String emailTo;

private String emailFrom;

private String subject;

@Column(columnDefinition = "TEXT")
private String text;

private LocalDateTime sendDataEmail;

private StatusEmail statusEmail;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package com.pet.foundation.pataamiga.domain.email;

public enum StatusEmail {
SENT,
ERROR
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.pet.foundation.pataamiga.domain.email.dto;

import lombok.Builder;
import lombok.Data;

@Data
@Builder
public class EmailDTO {
private String ownerRef;

private String emailTo;

private String emailFrom;

private String subject;
private String text;
private MailType mailType;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package com.pet.foundation.pataamiga.domain.email.dto;

public enum MailType {
CREATE_USER,
CHANGE_PASSWORD,
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ public class User implements UserDetails {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id = 0L;

@GeneratedValue(strategy = GenerationType.UUID)
private String uuid = "";

@Column(nullable = false)
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
@@ -0,0 +1,14 @@
package com.pet.foundation.pataamiga.mapper.email;

import com.pet.foundation.pataamiga.domain.email.Email;
import com.pet.foundation.pataamiga.domain.email.dto.EmailDTO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;

@Mapper(componentModel = "spring")
public interface EmailMapper {

EmailMapper INSTANCE = Mappers.getMapper(EmailMapper.class);

Email toEntity(EmailDTO emailDTO);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.pet.foundation.pataamiga.repositories;

import com.pet.foundation.pataamiga.domain.email.Email;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.UUID;

public interface EmailRepository extends JpaRepository<Email, UUID> {
}

This file was deleted.

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
@@ -0,0 +1,7 @@
package com.pet.foundation.pataamiga.service;

import com.pet.foundation.pataamiga.domain.email.dto.EmailDTO;

public interface EmailService {
void sendEmail(EmailDTO emailDTO);
}
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();
}
}
Loading

0 comments on commit f86955f

Please sign in to comment.