Skip to content

Commit

Permalink
Merge pull request #104 from Tech-Harbor/Bezsmertnyi
Browse files Browse the repository at this point in the history
Bezsmertnyi | http, fix, Update jwt
  • Loading branch information
Vladik-gif authored Apr 14, 2024
2 parents 61c4eab + 5d01267 commit b1f1e5a
Show file tree
Hide file tree
Showing 10 changed files with 93 additions and 22 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
Backend project marketplace
Backend project oranger

[Вимоги до API](https://github.com/Tech-Harbor/oranger_backend/blob/dev/documentation/Requirements.md)
50 changes: 50 additions & 0 deletions documentation/API.http
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
###Update Passsword JWT
PUT http://localhost:8080/api/change-password
Content-Type: application/json
Authorization: Bearer

{
"password": "Password325231"
}

###LinkEmail
POST http://localhost:8080/api/request/email
Content-Type: application/json

{
"email": "[email protected]"
}

###Register
POST http://localhost:8080/api/auth/signup
Content-Type: application/json

{
"lastname": "Vladik",
"firstname": "Bezsmertnyi",
"password": "Passwordq134",
"phone": "380732157991",
"email": "[email protected]"
}

###Login
POST http://localhost:8080/api/auth/login
Content-Type: application/json

{
"email": "[email protected]",
"password": "Passwordq134"
}

###Active User, JWT TOKEN
POST http://localhost:8080/api/active
Content-Type: application/x-www-form-urlencoded
Authorization: Bearer


###Accouth
GET http://localhost:8080/api/accouth
Content-Type: application/x-www-form-urlencoded

###Active Not Users
POST http://localhost:8080/api/sendEmailRegister
11 changes: 11 additions & 0 deletions documentation/Requirements.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
### Вимоги до Oranger API, cкладаються з таких пунктів:

1 Архітектура проекту
1.1 Кожен пакет проекту повинен відноситися лише до одної логіки цього пакету.
2 Класи і методи проекту
2.1 Кожна назва класу повинена передати всю логіку цього класу.
2.2 Кожен клас який має метод який не стосується логіки класу, повинен бути перенесений в новий клас цього
пакету (або в інший пакет за потребою).
2.3 Назва метода повинна передавати основну логіку або функціональність, яку він виконує.
2.4 Кожен клас, що включений в цей класи, повинні бути використаними.
3 Кожна залежність яка є в build.gradle повинна бути використана в API, обов'язково.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.example.backend.config.swagger;

import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeIn;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.info.Contact;
import io.swagger.v3.oas.annotations.info.Info;
Expand All @@ -16,8 +17,10 @@
)
@SecurityScheme(
name = "Bearer Authentication",
description = "JWT auth description",
scheme = "Bearer",
type = SecuritySchemeType.HTTP,
bearerFormat = "JWT",
scheme = "bearer"
in = SecuritySchemeIn.HEADER
)
public class OpenApiSwaggerConfig { }
4 changes: 2 additions & 2 deletions src/main/java/com/example/backend/mail/MailServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ private void sendRegistrationEmail(final UserEntity user) {
mimeMessage, false, UTF_8
);

helper.setSubject("Thank you for registration, " + user.getLastname());
helper.setSubject("???, " + user.getLastname());
helper.setTo(user.getEmail());
helper.setText(emailContent, true);

Expand Down Expand Up @@ -72,7 +72,7 @@ private void sendNewPassword(final UserEntity user) {
mimePasswordMessage, false, UTF_8
);

helper.setSubject("Account activation, " + user.getLastname());
helper.setSubject("Update Password, " + user.getLastname());
helper.setTo(user.getEmail());
helper.setText(passwordContent, true);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
Expand All @@ -32,16 +33,17 @@ protected void doFilterInternal(
final FilterChain filterChain) {

final String authHeader = request.getHeader(AUTHORIZATION);
final String jwt, userEmail;
final String jwt, userData;

if (authHeader != null && authHeader.startsWith(BEARER)) {
if (StringUtils.isNoneEmpty(authHeader) && authHeader.startsWith(BEARER)) {

jwt = authHeader.substring(7);
userEmail = jwtService.extractUserData(jwt);

if (userEmail != null && SecurityContextHolder.getContext().getAuthentication() == null) {
userData = jwtService.extractUserData(jwt);

MyUserDetails userDetails = (MyUserDetails) userDetailsService.loadUserByUsername(userEmail);
if (StringUtils.isNoneEmpty(userData) && SecurityContextHolder.getContext().getAuthentication() == null) {

MyUserDetails userDetails = (MyUserDetails) userDetailsService.loadUserByUsername(userData);

if (jwtService.isTokenValid(jwt, userDetails)) {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ public String extractUserData(final String token) {
return extractClaim(token, Claims::getSubject);
}

@Override
public boolean isTokenValid(final String token, final MyUserDetails userDetails) {
final String userEmail = extractUserData(token);
return userEmail.equals(userDetails.getUsername()) && !isTokenExpired(token);
}

@Override
public <T> T extractClaim(final String token, final Function<Claims, T> claimsResolver) {
final Claims claims = extractAllClaims(token);
Expand Down Expand Up @@ -81,12 +87,6 @@ private String generateJwtRefreshToken(final Map<String, Object> extraClaims, fi
.compact();
}

@Override
public boolean isTokenValid(final String token, final MyUserDetails userDetails) {
final String userEmail = extractUserData(token);
return userEmail.equals(userDetails.getUsername()) && !isTokenExpired(token);
}

private boolean isTokenExpired(final String token) {
return extractExpiration(token).before(new Date());
}
Expand Down
1 change: 1 addition & 0 deletions src/main/resources/application.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ spring:
provider:
google:
user-name-attribute: email

mail:
host: ${MAIL_HOST}
port: ${MAIL_PORT}
Expand Down
1 change: 0 additions & 1 deletion src/main/resources/templates/newPassword.ftlh
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Account activation, ${username}</title>
<style>
#body {
display: flex;
Expand Down
15 changes: 9 additions & 6 deletions src/main/resources/templates/register.ftlh
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Thank you for registration ${username}</title>
<style>
#body {
display: flex;
Expand All @@ -28,11 +27,15 @@
<body>
<div id="body">
<div id="div">
<h1 style="text-align: center">Registration</h1>
<p>Hello, ${username}!</p>
<p>This is a registration form. You can log in and use the online store application.</p>
<p>To activate the shape cabinet, follow the link</p>
<a href="https://oranger.store/?jwt=${jwt}">Oranger</a>
<h1 style="text-align: center">Шановний, ${username}!</h1>
<p>Ми раді повідомити Вам про успішну реєстрацію на нашому маркетплейсі Oranger.
Ваш обліковий запис був створений і готовий до використання.
Тепер Ви можете увійти на маркетплейс використовуючи логін і пароль,
які були вказали під час реєстрації.</p>

<p>Ми сподіваємося, що Ви отримаєте задоволення від використання нашого сервісу</p>

<p>З повагою, Команда <a href="https://oranger.store/?jwt=${jwt}">Oranger</a></p>
</div>
</div>
</body>
Expand Down

0 comments on commit b1f1e5a

Please sign in to comment.