Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix/auth token generation #93

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ public Email sendEmail(CreateEmailDto emailDto) {
email.setStatus(MailStatus.ERROR.name());
log.error("Failed to send email", mailException);
}

return this.emailRepository.save(email);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public Token generateAccessToken(String subject) {
return new Token(
Token.TokenType.ACCESS,
token,
duration,
tokenExpirationMsec,
LocalDateTime.ofInstant(expiryDate.toInstant(), ZoneId.systemDefault()));
}

Expand All @@ -65,7 +65,7 @@ public Token generateRefreshToken(String subject) {
return new Token(
Token.TokenType.REFRESH,
token,
duration,
refreshTokenExpirationMsec,
LocalDateTime.ofInstant(expiryDate.toInstant(), ZoneId.systemDefault()));
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
package com.fgc.combo.companion.controller;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.List;
import java.util.Optional;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureWebMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fgc.combo.companion.dto.CreateUserDto;
import com.fgc.combo.companion.dto.LoginRequest;
import com.fgc.combo.companion.dto.LoginResponse;
import com.fgc.combo.companion.dto.OAuthLoginRequestDto;
import com.fgc.combo.companion.enums.OAuthTypes;
import com.fgc.combo.companion.model.User;
import com.fgc.combo.companion.repository.UserRepository;
import com.fgc.combo.companion.service.UserService;

import jakarta.servlet.http.Cookie;
import lombok.extern.slf4j.Slf4j;

@SpringBootTest
@AutoConfigureWebMvc
@Slf4j
@ExtendWith(MockitoExtension.class)
@TestInstance(Lifecycle.PER_CLASS)
public class UserControllerTests {

private MockMvc mockMvc;

@Autowired
private WebApplicationContext applicationContext;

@Autowired
private UserService userService;

@Autowired
private UserRepository userRepository;

@Autowired
private ObjectMapper objectMapper;

private void assertSuccessResponse(int responseStatus) {
assertThat(responseStatus).isIn(List.of(200, 201));
}

@BeforeEach
public final void init() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(applicationContext).build();
}

private MockHttpServletResponse login(String url, Object body, User user) throws Exception {

MvcResult mvcResult = this.mockMvc.perform(
MockMvcRequestBuilders
.post(url)
.contentType("application/json")
.content(
objectMapper.writeValueAsString(body)))
.andReturn();

var mvcResponse = mvcResult.getResponse();

assertSuccessResponse(mvcResponse.getStatus());

LoginResponse loginResponse = objectMapper.readValue(
mvcResponse.getContentAsString(),
LoginResponse.class);

Cookie accessToken = mvcResponse.getCookie("accessToken");
if (user != null) {
assertThat(loginResponse.getUser().getId()).isEqualTo(user.getId());
}
assertThat(accessToken).isNotNull();
assertThat(accessToken.getDomain()).isEqualTo("fgc-combo-companion.xyz");
return mvcResponse;
}

@Test
@DisplayName("It should login with email and password")
void itShouldLoginSuccessfully() throws Exception {
var user = this.userService.create(
CreateUserDto.builder()
.email("[email protected]")
.password("12345678")
.name("USER")
.build());
this.login("/api/v1/users/login", new LoginRequest(user.getEmail(), "12345678"), user);
}

@Test
@DisplayName("It should login and create user if don't exist through OAuth")
void itShouldLoginAndCreateTheUserSuccessfullyThroughOAuth() throws Exception {

assertThat(userRepository.findUserByEmail("[email protected]")).isEmpty();
MockHttpServletResponse response = this.login("/api/v1/users/oauth/login",
new OAuthLoginRequestDto("[email protected]", OAuthTypes.GOOGLE.name(), "testname", "testauthkey", "123"),
null);

LoginResponse loginResponse = objectMapper.readValue(
response.getContentAsString(),
LoginResponse.class);

Optional<User> user = userRepository.findUserByEmail("[email protected]");

assertThat(user).isNotEmpty();
assertThat(user.get().getId()).isEqualTo(loginResponse.getUser().getId());

}

@Test
@DisplayName("It should login through OAuth")
void itShouldLoginThroughOAuth() throws Exception {

var user = this.userService.saveUser(User.builder().authProvider(OAuthTypes.GOOGLE).oAuthId("123456")
.email("[email protected]").emailVerified(true)
.name("test").build());

MockHttpServletResponse response = this.login("/api/v1/users/oauth/login",
new OAuthLoginRequestDto(user.getEmail(), OAuthTypes.GOOGLE.name(), user.getOAuthId(), "testauthkey",
user.getName()),
null);

LoginResponse loginResponse = objectMapper.readValue(
response.getContentAsString(),
LoginResponse.class);

assertThat(user.getId()).isEqualTo(loginResponse.getUser().getId());

}

}
6 changes: 3 additions & 3 deletions backend/src/test/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ server:
authentication:
auth:
secureKey: test
tokenSecret: SktwcElPMjNKNDIzTkFTREtKSHhjY3hhMjEzM0FTS0RGT0VXMzQzNDQyM04xM3NuZG1hczIxMjNMWENLTEpLcHBJTzIzSjQyM05BU0RLSkh4Y2N4YTIxMzNBU0tERk9FVzM0MzQ0MjNOMTNzbmRtYXMyMTIzTFhDS0xKS3BwSU8yM0o0MjNOQVNES0pIeGNjeGEyMTMzQVNLREZPRVczNDM0NDIzTjEzc25kbWFzMjEyM0xYQ0tMSktwcElPMjNKNDIzTkFTREtKSHhjY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IzTFhDS0xKS3BwSU8yM0o0MjNOQVNES0pIeGNjeGEyMTMzQVNLREZPRVczNDM0NDIzTjEzc25kbWFzMjEyM0xYQ0tMSktwcElPMjNKNDIzTkFTREtKSHhjY3hhMjEzM0FTS0RGT0VXMzQzNDQyM04xM3NuZG1hczIxMjNMWENLTEpLcHBJTzIzSjQyM05BU0RLSkh4Y2N4YTIxMzNBU0tERk9FVzM0MzQ0MjNOMTNzbmRtYXMyMTIzTFhDS0xKS3BwSU8yM0o0MjNOQVNES0pIeGNjeGEyMTMzQVNLREZPRVczNDM0NDIzTjEzc25kbWFzMjEyM0xYQ0tMSktwcElPMjNKNDIzTkFTREtKSHhjY3hhMjEzM0FTS0RGT0VXMzQzNDQyM04xM3NuZG1hczIxMjNMWENLTEpLcHBJTzIzSjQyM05BU0RLSkh4Y2N4YTIxMzNBU0tERk9FVzM0MzQ0MjNOMTNzbmRtYXMyMTIzTFhDS0xKS3BwSU8yM0o0MjNOQVNES0pIeGNjeGEyMTMzQVNLREZPRVczNDM0NDIzTjEzc25kbWFzMjEyM0xYQ0tM
tokenExpirationMsec: 777600
refreshTokenExpirationMsec: 777600
accessTokenCookieName: accessToken
refreshTokenCookieName: refreshToken
oauthkey: testauthkey
Expand Down
2 changes: 2 additions & 0 deletions backend/src/test/resources/import.sql
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
CREATE TYPE gametypes AS ENUM ('TEKKEN_7', 'SFV', 'STREET_FIGHTER_6','KOF_XV', 'GUILTY_GEAR_STRIVE', 'TEKKEN_8', 'MORTAL_KOMBAT_1')
CREATE TYPE mailstatustypes AS ENUM ('SENT', 'ERROR')
CREATE TYPE userverificationtypes AS ENUM ('PASSWORD_CHANGE', 'EMAIL_VERIFICATION')
CREATE TYPE oauthtypes AS ENUM ('GOOGLE');