Skip to content

Commit

Permalink
[Hexlet#159] fix redirection while getting exception
Browse files Browse the repository at this point in the history
  • Loading branch information
d1z3d committed Aug 17, 2024
1 parent 03b773b commit 964714f
Show file tree
Hide file tree
Showing 10 changed files with 57 additions and 18 deletions.
13 changes: 10 additions & 3 deletions src/main/java/io/hexlet/typoreporter/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import io.hexlet.typoreporter.config.oauth2.OAuth2ConfigurationProperties;
import io.hexlet.typoreporter.handler.exception.ForbiddenDomainException;
import io.hexlet.typoreporter.handler.exception.OAuth2Exception;
import io.hexlet.typoreporter.handler.exception.WorkspaceNotFoundException;
import io.hexlet.typoreporter.security.service.AccountDetailService;
import io.hexlet.typoreporter.security.service.SecuredWorkspaceService;
Expand All @@ -12,6 +13,7 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
Expand Down Expand Up @@ -98,6 +100,7 @@ public SecurityFilterChain filterChain(HttpSecurity http,
.requestMatchers(GET, "/webjars/**", "/widget/**", "/fragments/**", "/img/**").permitAll()
.requestMatchers("/", "/login", "/signup", "/error", "/about").permitAll()
.requestMatchers("/oauth/**").permitAll()
.requestMatchers("/login/oauth/code/**").permitAll()
.anyRequest().authenticated()
)
.formLogin(login -> login
Expand All @@ -108,8 +111,6 @@ public SecurityFilterChain filterChain(HttpSecurity http,
)
.oauth2Login(config -> config
.loginPage("/login")
.defaultSuccessUrl("/workspaces")
.failureUrl("/login")
)
.csrf(csrf -> csrf
.ignoringRequestMatchers(
Expand All @@ -134,11 +135,11 @@ private ClientRegistration githubClientRegistration() {
return CommonOAuth2Provider.GITHUB.getBuilder("github")
.clientId(oAuth2ConfigurationProperties.getClientId())
.clientSecret(oAuth2ConfigurationProperties.getClientSecret())
.redirectUri(oAuth2ConfigurationProperties.getRedirectUri())
.scope(oAuth2ConfigurationProperties.getScope())
.build();
}


@Bean
@RequestScope
public RestTemplate getRestTemplate() {
Expand Down Expand Up @@ -176,6 +177,12 @@ protected void doFilterInternal(HttpServletRequest request,
response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
} catch (WorkspaceNotFoundException e) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
} catch (OAuth2Exception e) {
if (e.getStatusCode() == HttpStatus.BAD_REQUEST) {
response.sendRedirect("/oauth/exception/name");
} else {
response.sendRedirect("/oauth/exception");
}
}
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,5 @@ public class OAuth2ConfigurationProperties {
private String clientSecret;
@Value("scope")
private HashSet<String> scope;
@Value("redirect-uri")
private String redirectUri;
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package io.hexlet.typoreporter.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/oauth")
public class OAuth2Controller {

@GetMapping("/exception")
public String handle(final Model model) {
model.addAttribute("isOAuth2Fail", true);
return "/login";
}

@GetMapping("/exception/name")
public String handleExceptionName(final Model model) {
model.addAttribute("isFullNameException", true);
return "/login";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,12 @@ public String getLogin() {
}
//TODO: fix required sets first and last names after issue #286 will be done (empty names)
public String getFirstName() {
String[] fullName = Objects.requireNonNull(oAuth2User.<String>getAttribute("name")).split(" ");
return fullName[1];
String[] fullName = oAuth2User.<String>getAttribute("name").split(" ");
return fullName[1] != null ? fullName[1] : "";
}
public String getLastName() {
String[] fullName = Objects.requireNonNull(oAuth2User.<String>getAttribute("name")).split(" ");
return fullName[0];
String[] fullName = oAuth2User.<String>getAttribute("name").split(" ");
return fullName[0] != null ? fullName[0] : "";
}
public String getPassword() {
Integer password = oAuth2User.getAttribute("id");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,16 @@
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class CustomOAuth2UserService extends DefaultOAuth2UserService {
private final GithubService githubService;
private final AccountService accountService;
private final GithubService githubService;

public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
public OAuth2User loadUser(OAuth2UserRequest userRequest) {
OAuth2User user = super.loadUser(userRequest);
var email = githubService.getPrivateEmail(userRequest.getAccessToken().getTokenValue());
var customUser = new CustomOAuth2User(user, email);
Expand Down
15 changes: 11 additions & 4 deletions src/main/java/io/hexlet/typoreporter/service/AccountService.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@
import io.hexlet.typoreporter.domain.account.Account;
import io.hexlet.typoreporter.domain.account.AuthProvider;
import io.hexlet.typoreporter.domain.account.CustomOAuth2User;
import io.hexlet.typoreporter.handler.exception.AccountAlreadyExistException;
import io.hexlet.typoreporter.handler.exception.AccountNotFoundException;
import io.hexlet.typoreporter.handler.exception.NewPasswordTheSameException;
import io.hexlet.typoreporter.handler.exception.OAuth2Exception;
import io.hexlet.typoreporter.handler.exception.OldPasswordWrongException;
import io.hexlet.typoreporter.repository.AccountRepository;
import io.hexlet.typoreporter.repository.WorkspaceRoleRepository;
import io.hexlet.typoreporter.service.account.EmailAlreadyExistException;
Expand All @@ -16,11 +21,9 @@
import io.hexlet.typoreporter.service.mapper.AccountMapper;
import io.hexlet.typoreporter.service.mapper.WorkspaceRoleMapper;
import io.hexlet.typoreporter.utils.TextUtils;
import io.hexlet.typoreporter.handler.exception.AccountAlreadyExistException;
import io.hexlet.typoreporter.handler.exception.AccountNotFoundException;
import io.hexlet.typoreporter.handler.exception.NewPasswordTheSameException;
import io.hexlet.typoreporter.handler.exception.OldPasswordWrongException;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand Down Expand Up @@ -141,6 +144,10 @@ public Account updatePassword(final UpdatePassword updatePassword, final String
}
@Transactional
public void processOAuthPostLogin(CustomOAuth2User user) {
if (user.getFirstName().isEmpty() || user.getLastName().isEmpty()) {
throw new OAuth2Exception(HttpStatus.BAD_REQUEST,
ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Firstname or lastname is empty"), null);
}
var existUser = accountRepository.existsByEmail(user.getEmail());
if (!existUser) {
SignupAccount signupAccount = new SignupAccount(
Expand Down
1 change: 0 additions & 1 deletion src/main/resources/config/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ spring:
github:
clientId: Ov23liMZqO6eA0FyjeM4
clientSecret: 3948c7b7ac39d2ee6611e611259c9422cdf00f96
redirect-uri: "{baseUrl}/workspaces"
scope:
- user:email
- read:user
2 changes: 2 additions & 0 deletions src/main/resources/messages_en.properties
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ btn.restart=RESTART
btn.cancel=CANCEL

alert.bad-credential=Bad credential
alert.oauth2.exception=Github authorization error
alert.oauth2.exception.name=You must have your first and last name filled in Github
alert.logout=You have been logged out
link.signup=Sign Up

Expand Down
2 changes: 2 additions & 0 deletions src/main/resources/messages_ru.properties
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ btn.login=Войти
link.signup=Регистрация
alert.logout=Вы были разлогинены
alert.bad-credential=Неверные логин и/или пароль
alert.oauth2.exception=Ошибка авторизации
alert.oauth2.exception.name=Заполните имя и фамилию в профиле Github

navbar.login=Войти
navbar.logout=Выход
Expand Down
4 changes: 3 additions & 1 deletion src/main/resources/templates/login.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
<main class="container">
<div class="row">
<div class="col">
<div class="invalid-feedback" role="alert" th:if="${param.error}" th:text="#{alert.bad-credential}"></div>
<div class="alert alert-danger" role="alert" th:if="${param.error}" th:text="#{alert.bad-credential}"></div>
<div class="alert alert-danger" role="alert" th:if="${isOAuth2Fail}" th:text="#{alert.oauth2.exception}"></div>
<div class="alert alert-danger" role="alert" th:if="${isFullNameException}" th:text="#{alert.oauth2.exception.name}"></div>
<div class="alert alert-warning" role="alert" th:if="${param.logout}" th:text="#{alert.logout}"></div>
<form method="post" th:action="@{/login}">
<div class="form-floating mb-3">
Expand Down

0 comments on commit 964714f

Please sign in to comment.