@ -1,13 +1,16 @@
package org.ccalm.jwt ;
package org.ccalm.jwt ;
import com.fasterxml.jackson.annotation.JsonProperty ;
import io.swagger.v3.oas.annotations.Operation ;
import io.swagger.v3.oas.annotations.Operation ;
import io.swagger.v3.oas.annotations.media.Content ;
import io.swagger.v3.oas.annotations.media.Content ;
import io.swagger.v3.oas.annotations.media.Schema ;
import io.swagger.v3.oas.annotations.media.Schema ;
import io.swagger.v3.oas.annotations.responses.ApiResponse ;
import io.swagger.v3.oas.annotations.responses.ApiResponse ;
import com.warrenstrange.googleauth.GoogleAuthenticator ;
import com.warrenstrange.googleauth.GoogleAuthenticator ;
import com.warrenstrange.googleauth.GoogleAuthenticatorKey ;
import com.warrenstrange.googleauth.GoogleAuthenticatorKey ;
import org.apache.commons.codec.digest.DigestUtils ;
import org.ccalm.jwt.models.* ;
import org.ccalm.jwt.models.* ;
import org.ccalm.jwt.tools.* ;
import org.ccalm.jwt.tools.* ;
import org.ccalm.jwt.tools.* ;
import com.zaxxer.hikari.HikariDataSource ;
import com.zaxxer.hikari.HikariDataSource ;
import io.jsonwebtoken.* ;
import io.jsonwebtoken.* ;
import jakarta.servlet.ServletContext ;
import jakarta.servlet.ServletContext ;
@ -52,9 +55,11 @@ import javax.mail.MessagingException;
import java.awt.* ;
import java.awt.* ;
import java.awt.image.BufferedImage ;
import java.awt.image.BufferedImage ;
import java.io.* ;
import java.io.* ;
import java.security.SecureRandom ;
import java.security.spec.PKCS8EncodedKeySpec ;
import java.security.spec.PKCS8EncodedKeySpec ;
import java.security.spec.X509EncodedKeySpec ;
import java.security.spec.X509EncodedKeySpec ;
import java.sql.Date ;
import java.sql.Date ;
import java.sql.Types ;
import java.time.Duration ;
import java.time.Duration ;
import java.time.Instant ;
import java.time.Instant ;
import java.util.* ;
import java.util.* ;
@ -66,6 +71,8 @@ import java.io.IOException;
import java.util.stream.Collectors ;
import java.util.stream.Collectors ;
import org.springframework.security.core.Authentication ;
import org.springframework.security.core.Authentication ;
import org.springframework.core.env.Environment ;
import org.springframework.core.env.Environment ;
import org.springframework.transaction.annotation.Transactional ;
@Controller
@Controller
public class MainController implements ServletContextAware {
public class MainController implements ServletContextAware {
@ -343,7 +350,7 @@ public class MainController implements ServletContextAware {
//json.put("idle_connections",dataSource.getHikariPoolMXBean().getIdleConnections());
//json.put("idle_connections",dataSource.getHikariPoolMXBean().getIdleConnections());
// Вывод всех зарегистрированных маршрутов в системе
// Вывод всех зарегистрированных маршрутов в системе
ApplicationContext context = SpringContext. getApplicationContext( ) ;
/* ApplicationContext context = SpringContext. getApplicationContext();
if (context != null) {
if (context != null) {
RequestMappingHandlerMapping mapping = context.getBean(RequestMappingHandlerMapping.class);
RequestMappingHandlerMapping mapping = context.getBean(RequestMappingHandlerMapping.class);
Set<String> endpoints = mapping.getHandlerMethods().keySet().stream()
Set<String> endpoints = mapping.getHandlerMethods().keySet().stream()
@ -351,7 +358,7 @@ public class MainController implements ServletContextAware {
.collect(Collectors.toSet());
.collect(Collectors.toSet());
System.out.println("=== Registered API endpoints ===");
System.out.println("=== Registered API endpoints ===");
endpoints.forEach(System.out::println);
endpoints.forEach(System.out::println);
}
}*/
} catch ( JSONException e ) {
} catch ( JSONException e ) {
throw new RuntimeException ( e ) ;
throw new RuntimeException ( e ) ;
@ -367,7 +374,7 @@ public class MainController implements ServletContextAware {
try {
try {
if ( jwt_a . isEmpty ( ) | | countOccurrences ( jwt_a , '.' ) ! = 2 )
if ( jwt_a . isEmpty ( ) | | countOccurrences ( jwt_a , '.' ) ! = 2 )
{
{
throw new CustomException ( 10000 , trt . trt ( false , " Please_log_in " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " Please_log_in " ) , null , false );
}
}
Jws < Claims > claims = null ;
Jws < Claims > claims = null ;
try {
try {
@ -376,7 +383,7 @@ public class MainController implements ServletContextAware {
. build ( )
. build ( )
. parseClaimsJws ( jwt_a ) ;
. parseClaimsJws ( jwt_a ) ;
} catch ( Exception e ) {
} catch ( Exception e ) {
throw new CustomException ( 10000 , trt . trt ( false , " Please_log_in " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " Please_log_in " ) , null , false );
}
}
String sql = " " "
String sql = " " "
select
select
@ -413,7 +420,7 @@ public class MainController implements ServletContextAware {
try {
try {
if ( jwt_a . isEmpty ( ) | | countOccurrences ( jwt_a , '.' ) ! = 2 )
if ( jwt_a . isEmpty ( ) | | countOccurrences ( jwt_a , '.' ) ! = 2 )
{
{
throw new CustomException ( 10000 , trt . trt ( false , " Please_log_in " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " Please_log_in " ) , null , false );
}
}
//Проверяю подпись токена
//Проверяю подпись токена
Jws < Claims > claims = null ;
Jws < Claims > claims = null ;
@ -423,7 +430,7 @@ public class MainController implements ServletContextAware {
. build ( )
. build ( )
. parseClaimsJws ( jwt_a ) ;
. parseClaimsJws ( jwt_a ) ;
} catch ( Exception e ) {
} catch ( Exception e ) {
throw new CustomException ( 10000 , Arrays . asList ( trt . trt ( false , " Please_log_in " ) , trt . trt ( false , " JWT_token_verification_error " ) ) , null ) ;
throw new CustomException ( 10000 , Arrays . asList ( trt . trt ( false , " Please_log_in " ) , trt . trt ( false , " JWT_token_verification_error " ) ) , null , false );
}
}
//TODO проверить доступ для выполнения данной функции
//TODO проверить доступ для выполнения данной функции
//Выполняем функцию
//Выполняем функцию
@ -589,7 +596,7 @@ public class MainController implements ServletContextAware {
} catch ( IOException e ) {
} catch ( IOException e ) {
String uuid = UUID . randomUUID ( ) . toString ( ) ;
String uuid = UUID . randomUUID ( ) . toString ( ) ;
logger . error ( uuid , e ) ;
logger . error ( uuid , e ) ;
throw new CustomException ( 10000 , trt . trt ( false , " Input_output_error " ) , uuid ) ;
throw new CustomException ( 10000 , trt . trt ( false , " Input_output_error " ) , uuid , false );
}
}
//Формирую JSON токена и шифрую е г о
//Формирую JSON токена и шифрую е г о
@ -612,7 +619,8 @@ public class MainController implements ServletContextAware {
return json . toString ( ) ;
return json . toString ( ) ;
}
}
//------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------
@Operation ( summary = " Create new user account " , description = " " )
@Transactional
@Operation ( summary = " Create new user account " , description = " After creating a user, adding a default user role " )
@RequestMapping ( value = " /create " , method = RequestMethod . POST , produces = " application/json;charset=utf-8 " )
@RequestMapping ( value = " /create " , method = RequestMethod . POST , produces = " application/json;charset=utf-8 " )
@ResponseBody
@ResponseBody
public String create ( @RequestBody NewUserModel newUserModel , @RequestParam ( required = false , name = " lng " , defaultValue = " 1 " ) String language_id ) {
public String create ( @RequestBody NewUserModel newUserModel , @RequestParam ( required = false , name = " lng " , defaultValue = " 1 " ) String language_id ) {
@ -623,19 +631,19 @@ public class MainController implements ServletContextAware {
json . put ( " error_message " , " " ) ;
json . put ( " error_message " , " " ) ;
if ( newUserModel . getName ( ) . length ( ) < 3 ) {
if ( newUserModel . getName ( ) . length ( ) < 3 ) {
throw new CustomException ( 10000 , trt . trt ( false , " The_name_field_is_empty " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_name_field_is_empty " ) , null , false );
}
}
if ( newUserModel . getEmail ( ) . length ( ) < 6 ) {
if ( newUserModel . getEmail ( ) . length ( ) < 6 ) {
throw new CustomException ( 10000 , trt . trt ( false , " The_email_field_is_empty " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_email_field_is_empty " ) , null , false );
}
}
if ( ! Tools . isValidEmail ( newUserModel . getEmail ( ) ) ) {
if ( ! Tools . isValidEmail ( newUserModel . getEmail ( ) ) ) {
throw new CustomException ( 10000 , trt . trt ( false , " The_email_field_is_incorrect " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_email_field_is_incorrect " ) , null , false );
}
}
if ( newUserModel . getCode ( ) . length ( ) < 3 ) {
if ( newUserModel . getCode ( ) . length ( ) < 3 ) {
throw new CustomException ( 10000 , trt . trt ( false , " The_code_field_is_empty " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_code_field_is_empty " ) , null , false );
}
}
if ( newUserModel . getToken ( ) . length ( ) < 3 ) {
if ( newUserModel . getToken ( ) . length ( ) < 3 ) {
throw new CustomException ( 10000 , trt . trt ( false , " The_token_field_is_empty " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_token_field_is_empty " ) , null , false );
}
}
//Проверяю что подпись одинакова
//Проверяю что подпись одинакова
@ -644,7 +652,7 @@ public class MainController implements ServletContextAware {
String signature2 = Tools . generateSignature ( captchaKey , payload ) ;
String signature2 = Tools . generateSignature ( captchaKey , payload ) ;
if ( ! signature1 . equals ( signature2 ) ) {
if ( ! signature1 . equals ( signature2 ) ) {
throw new CustomException ( 10000 , trt . trt ( false , " The_signature_did_not_match " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_signature_did_not_match " ) , null , false );
}
}
//Расшифровываю
//Расшифровываю
String sToken = Tools . decryptText ( captchaKey , payload ) ;
String sToken = Tools . decryptText ( captchaKey , payload ) ;
@ -657,19 +665,19 @@ public class MainController implements ServletContextAware {
}
}
if ( jToken = = null ) {
if ( jToken = = null ) {
throw new CustomException ( 10000 , trt . trt ( false , " Please_send_a_valid_JSON_string_in_your_token " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " Please_send_a_valid_JSON_string_in_your_token " ) , null , false );
}
}
if ( ! newUserModel . getCode ( ) . equals ( jToken . getString ( " code " ) ) ) {
if ( ! newUserModel . getCode ( ) . equals ( jToken . getString ( " code " ) ) ) {
throw new CustomException ( 10000 , trt . trt ( false , " The_code_did_not_match_what_was_specified_in_the_captcha " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_code_did_not_match_what_was_specified_in_the_captcha " ) , null , false );
}
}
if ( jToken . getLong ( " exp " ) < ( System . currentTimeMillis ( ) / 1000L ) ) {
if ( jToken . getLong ( " exp " ) < ( System . currentTimeMillis ( ) / 1000L ) ) {
throw new CustomException ( 10000 , trt . trt ( false , " Captcha_is_outdated " ) , null ) ;
throw new CustomException ( 10000 , List . of ( trt. trt ( false , " Captcha_is_outdated " ) , trt . trt ( false , " Please_update_the_captcha " ) ) , null , false ) ;
}
}
if ( ! Tools . isValidEmail ( jToken . getString ( " email " ) ) ) {
if ( ! Tools . isValidEmail ( jToken . getString ( " email " ) ) ) {
throw new CustomException ( 10000 , trt . trt ( false , " The_email_field_is_incorrect " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_email_field_is_incorrect " ) , null , false );
}
}
if ( ! newUserModel . getEmail ( ) . equals ( jToken . getString ( " email " ) ) ) {
if ( ! newUserModel . getEmail ( ) . equals ( jToken . getString ( " email " ) ) ) {
throw new CustomException ( 10000 , trt . trt ( false , " The_email_did_not_match_what_was_specified_in_the_captcha " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_email_did_not_match_what_was_specified_in_the_captcha " ) , null , false );
}
}
//Проверяю существование пользователя с таким email
//Проверяю существование пользователя с таким email
@ -680,7 +688,7 @@ public class MainController implements ServletContextAware {
parameters . addValue ( " email " , newUserModel . getEmail ( ) ) ;
parameters . addValue ( " email " , newUserModel . getEmail ( ) ) ;
List < String > ret = jdbcTemplate . query ( sql , parameters , new DBTools . JsonRowMapper ( ) ) ;
List < String > ret = jdbcTemplate . query ( sql , parameters , new DBTools . JsonRowMapper ( ) ) ;
for ( int i = 0 ; i < ret . size ( ) ; i + + ) {
for ( int i = 0 ; i < ret . size ( ) ; i + + ) {
throw new CustomException ( 10000 , trt . trt ( false , " A_user_with_the_same_email_address_already_exists " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " A_user_with_the_same_email_address_already_exists " ) , null , false );
}
}
// Генерируем временный пароль
// Генерируем временный пароль
@ -693,34 +701,51 @@ public class MainController implements ServletContextAware {
//Добавляем пользователя
//Добавляем пользователя
sql = """
sql = """
insert into main._users(
insert into main._users(
_user_id, name, email, e_iin, password, expiration
_user_u id,
country_uid,
name,
e_surname,
company,
position,
e_phone,
email,
password,
expiration
)values(
)values(
1, :name, :email, pgp_sym_encrypt(:e_iin,:key), crypt(:password, gen_salt('bf')), now()+interval '5 day'
null,
(select uid from main.countries where del=false and code3=:code3 limit 1),
:name,
pgp_sym_encrypt(CAST(:e_surname AS TEXT), CAST(:key AS TEXT)),
:company,
:position,
pgp_sym_encrypt(CAST(:e_phone AS TEXT), CAST(:key AS TEXT)),
:email,
crypt(:password, gen_salt('bf')),
now()+interval '5 day'
) RETURNING id;
) RETURNING id;
""" ;
""" ;
parameters = new MapSqlParameterSource ( ) ;
parameters = new MapSqlParameterSource ( ) ;
//parameters.addValue("country_id",);
// parameters. addValue("company_name",);
parameters. addValue( " code3 " , newUserModel . getCountry ( ) , Types . VARCHAR ) ; // country
// parameters. addValue("position",) ;
parameters. addValue( " name " , newUserModel . getName ( ) , Types . VARCHAR ) ;
parameters . addValue ( " name " , newUserModel . getN ame ( ) ) ;
parameters . addValue ( " e_sur name" , newUserModel . getSurn ame ( ) , Types . VARCHAR );
// parameters. addValue("surname",) ;
parameters. addValue( " company " , newUserModel . getCompany ( ) , Types . VARCHAR ) ;
// parameters. addValue("patronymic",) ;
parameters. addValue( " position " , newUserModel . getPosition ( ) , Types . VARCHAR ) ;
// parameters. addValue("phone",) ;
parameters. addValue( " e_phone " , newUserModel . getPhone ( ) , Types . VARCHAR ) ;
parameters . addValue ( " email " , newUserModel . getEmail ( ) ) ;
parameters . addValue ( " email " , newUserModel . getEmail ( ) , Types . VARCHAR );
parameters . addValue ( " e_iin " , newUserModel . getIin ( ) ) ; //Для ЭЦП это поле обязательно
parameters . addValue ( " key " , personal_data_key , Types . VARCHAR ) ;
parameters . addValue ( " key " , personal_data_key ) ;
parameters . addValue ( " password " , password , Types . VARCHAR ) ;
parameters . addValue ( " password " , password ) ;
ret = jdbcTemplate . query ( sql , parameters , new DBTools . JsonRowMapper ( ) ) ;
ret = jdbcTemplate . query ( sql , parameters , new DBTools . JsonRowMapper ( ) ) ;
for ( int i = 0 ; i < ret . size ( ) ; i + + ) {
for ( int i = 0 ; i < ret . size ( ) ; i + + ) {
JSONObject obj = new JSONObject ( ret . get ( i ) ) ;
JSONObject obj = new JSONObject ( ret . get ( i ) ) ;
//Добавляю роль перевозчика пользователю
//Добавляю роль по умолчанию для пользователя
sql = """
sql = """
insert into main._usersgroups(user_id,group_id)values(:id,12) RETURNING id ;
insert into main._usersgroups(user_id,group_id) select :id, g.id from main._groups g where g.del=false and g.default=true ;
""" ;
""" ;
parameters = new MapSqlParameterSource ( ) ;
parameters = new MapSqlParameterSource ( ) ;
parameters . addValue ( " id " , obj . getLong ( " id " ) ) ;
parameters . addValue ( " id " , obj . getLong ( " id " ) ) ;
jdbcTemplate . query ( sql , parameters , new DBTools . JsonRowMapper ( ) );
jdbcTemplate . update ( sql , parameters ) ;
}
}
//Отправляю пароль на почту с ссылкой на активацию этого пользователя
//Отправляю пароль на почту с ссылкой на активацию этого пользователя
@ -734,7 +759,7 @@ public class MainController implements ServletContextAware {
try {
try {
EmailUtility . sendEmail ( mail_host , mail_port , mail_login , mail_password , newUserModel . getEmail ( ) , trt . trt ( true , " Password " ) , html ) ;
EmailUtility . sendEmail ( mail_host , mail_port , mail_login , mail_password , newUserModel . getEmail ( ) , trt . trt ( true , " Password " ) , html ) ;
} catch ( MessagingException e ) {
} catch ( MessagingException e ) {
throw new CustomException ( 10000 , String . format ( trt . trt ( false , " Failed_send_mail_to_s " ) , newUserModel . getEmail ( ) ) , null ) ;
throw new CustomException ( 10000 , String . format ( trt . trt ( false , " Failed_send_mail_to_s " ) , newUserModel . getEmail ( ) ) , null , false );
}
}
json . put ( " error_message " , trt . trt ( false , " The_authorization_password_has_been_sent_to_your_email_address " ) ) ;
json . put ( " error_message " , trt . trt ( false , " The_authorization_password_has_been_sent_to_your_email_address " ) ) ;
@ -761,7 +786,7 @@ public class MainController implements ServletContextAware {
if ( jwt_a . isEmpty ( ) | | countOccurrences ( jwt_a , '.' ) ! = 2 )
if ( jwt_a . isEmpty ( ) | | countOccurrences ( jwt_a , '.' ) ! = 2 )
{
{
throw new CustomException ( 10000 , trt . trt ( false , " Please_log_in " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " Please_log_in " ) , null , false );
}
}
//Проверяю подпись токена
//Проверяю подпись токена
Jws < Claims > claims = null ;
Jws < Claims > claims = null ;
@ -771,7 +796,7 @@ public class MainController implements ServletContextAware {
. build ( )
. build ( )
. parseClaimsJws ( jwt_a ) ;
. parseClaimsJws ( jwt_a ) ;
} catch ( Exception e ) {
} catch ( Exception e ) {
throw new CustomException ( 10000 , Arrays . asList ( trt . trt ( false , " Please_log_in " ) , trt . trt ( false , " JWT_token_verification_error " ) ) , null ) ;
throw new CustomException ( 10000 , Arrays . asList ( trt . trt ( false , " Please_log_in " ) , trt . trt ( false , " JWT_token_verification_error " ) ) , null , false );
}
}
//Выбираю данные о пользователе (TODO наверно стоит вызывать функцию get_user_info также и при логине)
//Выбираю данные о пользователе (TODO наверно стоит вызывать функцию get_user_info также и при логине)
@ -787,15 +812,15 @@ public class MainController implements ServletContextAware {
} catch ( Exception ex ) {
} catch ( Exception ex ) {
String uuid = UUID . randomUUID ( ) . toString ( ) ;
String uuid = UUID . randomUUID ( ) . toString ( ) ;
logger . error ( uuid , ex ) ;
logger . error ( uuid , ex ) ;
throw new CustomException ( 10000 , trt . trt ( false , " Error_executing_SQL_query " ) , uuid ) ;
throw new CustomException ( 10000 , trt . trt ( false , " Error_executing_SQL_query " ) , uuid , false );
}
}
if ( json = = null ) {
if ( json = = null ) {
throw new CustomException ( 10000 , trt . trt ( false , " Invalid_username_and_or_password " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " Invalid_username_and_or_password " ) , null , false );
} else {
} else {
if ( json . has ( " block " ) ) {
if ( json . has ( " block " ) ) {
if ( ! json . isNull ( " block " ) & & json . getBoolean ( " block " ) )
if ( ! json . isNull ( " block " ) & & json . getBoolean ( " block " ) )
throw new CustomException ( 10006 , trt . trt ( false , " The_user_account_is_blocked " ) , null ) ;
throw new CustomException ( 10006 , trt . trt ( false , " The_user_account_is_blocked " ) , null , false );
json . remove ( " block " ) ;
json . remove ( " block " ) ;
}
}
@ -830,15 +855,15 @@ public class MainController implements ServletContextAware {
json . put ( " error_message " , " " ) ;
json . put ( " error_message " , " " ) ;
if ( loginModel . getLogin ( ) . isEmpty ( ) )
if ( loginModel . getLogin ( ) . isEmpty ( ) )
throw new CustomException ( 10000 , trt . trt ( false , " The_login_field_is_empty " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_login_field_is_empty " ) , null , false );
if ( ! Tools . isValidEmail ( loginModel . getLogin ( ) ) )
if ( ! Tools . isValidEmail ( loginModel . getLogin ( ) ) )
throw new CustomException ( 10000 , trt . trt ( false , " The_login_field_is_incorrect " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_login_field_is_incorrect " ) , null , false );
if ( loginModel . getPassword ( ) . isEmpty ( ) )
if ( loginModel . getPassword ( ) . isEmpty ( ) )
throw new CustomException ( 10000 , trt . trt ( false , " The_password_field_is_empty " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_password_field_is_empty " ) , null , false );
if ( loginModel . getPassword ( ) . length ( ) < = 3 )
if ( loginModel . getPassword ( ) . length ( ) < = 3 )
throw new CustomException ( 10000 , trt . trt ( false , " The_password_field_is_short " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_password_field_is_short " ) , null , false );
if ( loginModel . getAppid ( ) . isEmpty ( ) )
if ( loginModel . getAppid ( ) . isEmpty ( ) )
throw new CustomException ( 10000 , trt . trt ( false , " The_application_name_field_is_empty " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_application_name_field_is_empty " ) , null , false );
String ipAddress = request . getHeader ( " X-FORWARDED-FOR " ) ; //Н е беспокойся на регистр не обращает внимания
String ipAddress = request . getHeader ( " X-FORWARDED-FOR " ) ; //Н е беспокойся на регистр не обращает внимания
if ( ipAddress = = null ) {
if ( ipAddress = = null ) {
@ -907,19 +932,19 @@ public class MainController implements ServletContextAware {
} catch ( DataAccessException ex ) {
} catch ( DataAccessException ex ) {
String uuid = UUID . randomUUID ( ) . toString ( ) ;
String uuid = UUID . randomUUID ( ) . toString ( ) ;
logger . error ( uuid , ex ) ;
logger . error ( uuid , ex ) ;
throw new CustomException ( 10000 , trt . trt ( false , " Internal_Server_Error " ) , uuid ) ;
throw new CustomException ( 10000 , trt . trt ( false , " Internal_Server_Error " ) , uuid , false );
}
}
if ( json = = null ) {
if ( json = = null ) {
String msg = trt . trt ( false , " Invalid_username_and_or_password " ) ;
String msg = trt . trt ( false , " Invalid_username_and_or_password " ) ;
if ( attempt_count > 0 ) {
if ( attempt_count > 0 ) {
msg = msg + " " + String . format ( trt . trt ( false , " Authorization_attempts_s_out_of_s " ) , attempt_count , attempt_limit ) ;
msg = msg + " " + String . format ( trt . trt ( false , " Authorization_attempts_s_out_of_s " ) , attempt_count , attempt_limit ) ;
}
}
throw new CustomException ( 10000 , msg , null ) ;
throw new CustomException ( 10000 , msg , null , false );
}
}
if ( json . has ( " block " ) ) {
if ( json . has ( " block " ) ) {
if ( json . getBoolean ( " block " ) ) {
if ( json . getBoolean ( " block " ) ) {
throw new CustomException ( 10006 , trt . trt ( false , " The_user_account_is_blocked " ) , ( String ) null ) ;
throw new CustomException ( 10006 , trt . trt ( false , " The_user_account_is_blocked " ) , ( String ) null , false );
}
}
json . remove ( " block " ) ;
json . remove ( " block " ) ;
@ -927,11 +952,11 @@ public class MainController implements ServletContextAware {
long currentTime = System . currentTimeMillis ( ) / 1000L ;
long currentTime = System . currentTimeMillis ( ) / 1000L ;
if ( json . has ( " expiration " ) & & json . getLong ( " expiration " ) < currentTime ) {
if ( json . has ( " expiration " ) & & json . getLong ( " expiration " ) < currentTime ) {
throw new CustomException ( 10009 , trt . trt ( false , " Password_expired_and_must_be_changed " ) , ( String ) null ) ;
throw new CustomException ( 10009 , trt . trt ( false , " Password_expired_and_must_be_changed " ) , ( String ) null , false );
}
}
if ( json . has ( " totp_required " ) & & ! json . isNull ( " totp_required " ) & & json . getBoolean ( " totp_required " ) & & json . has ( " totp_key " ) & & json . isNull ( " totp_key " ) ) {
if ( json . has ( " totp_required " ) & & ! json . isNull ( " totp_required " ) & & json . getBoolean ( " totp_required " ) & & json . has ( " totp_key " ) & & json . isNull ( " totp_key " ) ) {
throw new CustomException ( 10010 , trt . trt ( false , " You_need_to_get_a_new_TOTP_key " ) , ( String ) null ) ;
throw new CustomException ( 10010 , trt . trt ( false , " You_need_to_get_a_new_TOTP_key " ) , ( String ) null , false );
}
}
ArrayList errorMessages ;
ArrayList errorMessages ;
@ -947,7 +972,7 @@ public class MainController implements ServletContextAware {
errorSettings . add ( str + " ; " + String . valueOf ( attempt_limit ) + " ; " ) ;
errorSettings . add ( str + " ; " + String . valueOf ( attempt_limit ) + " ; " ) ;
}
}
throw new CustomException ( 10012 , errorMessages , errorSettings , ( String ) null ) ;
throw new CustomException ( 10012 , errorMessages , errorSettings , ( String ) null , false );
}
}
if ( json . has ( " totp_success " ) & & ! json . getBoolean ( " totp_success " ) ) {
if ( json . has ( " totp_success " ) & & ! json . getBoolean ( " totp_success " ) ) {
@ -961,7 +986,7 @@ public class MainController implements ServletContextAware {
errorSettings . add ( str + " ; " + String . valueOf ( attempt_limit ) + " ; " ) ;
errorSettings . add ( str + " ; " + String . valueOf ( attempt_limit ) + " ; " ) ;
}
}
throw new CustomException ( 10000 , errorMessages , errorSettings , ( String ) null ) ;
throw new CustomException ( 10000 , errorMessages , errorSettings , ( String ) null , false );
}
}
if ( json . has ( " totp_required " ) ) {
if ( json . has ( " totp_required " ) ) {
@ -989,7 +1014,7 @@ public class MainController implements ServletContextAware {
} catch ( Exception ex ) {
} catch ( Exception ex ) {
String uuid = UUID . randomUUID ( ) . toString ( ) ;
String uuid = UUID . randomUUID ( ) . toString ( ) ;
logger . error ( uuid , ex ) ;
logger . error ( uuid , ex ) ;
throw new CustomException ( 10000 , trt . trt ( false , " Error_executing_SQL_query " ) , uuid ) ;
throw new CustomException ( 10000 , trt . trt ( false , " Error_executing_SQL_query " ) , uuid , false );
}
}
//SecretKey key_a = new SecretKeySpec(Base64.getDecoder().decode(key_a_txt), "HmacSHA256");
//SecretKey key_a = new SecretKeySpec(Base64.getDecoder().decode(key_a_txt), "HmacSHA256");
@ -1110,9 +1135,9 @@ public class MainController implements ServletContextAware {
if ( ! json . has ( " result " ) | | json . getBoolean ( " result " ) ) {
if ( ! json . has ( " result " ) | | json . getBoolean ( " result " ) ) {
if ( json . getInt ( " count " ) = = 0 )
if ( json . getInt ( " count " ) = = 0 )
{
{
throw new CustomException ( 10000 , trt . trt ( false , " The_user_account_is_blocked " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_user_account_is_blocked " ) , null , false );
} else {
} else {
throw new CustomException ( 10000 , java . lang . String . format ( trt . trt ( false , " The_limit_of_authorization_attempts_has_been_exceeded_please_wait_s_minutes " ) , json . getInt ( " limit_duration " ) ) , null ) ;
throw new CustomException ( 10000 , java . lang . String . format ( trt . trt ( false , " The_limit_of_authorization_attempts_has_been_exceeded_please_wait_s_minutes " ) , json . getInt ( " limit_duration " ) ) , null , false );
}
}
}
}
if ( json . has ( " count " ) & & json . has ( " limit_count " ) & & json . has ( " limit_duration " ) ) {
if ( json . has ( " count " ) & & json . has ( " limit_count " ) & & json . has ( " limit_duration " ) ) {
@ -1124,11 +1149,11 @@ public class MainController implements ServletContextAware {
} catch ( DataAccessException ex ) {
} catch ( DataAccessException ex ) {
java . lang . String uuid = UUID . randomUUID ( ) . toString ( ) ;
java . lang . String uuid = UUID . randomUUID ( ) . toString ( ) ;
logger . error ( uuid , ex ) ;
logger . error ( uuid , ex ) ;
throw new CustomException ( 10000 , trt . trt ( false , " Internal_Server_Error " ) , uuid ) ;
throw new CustomException ( 10000 , trt . trt ( false , " Internal_Server_Error " ) , uuid , false );
} catch ( Exception e ) {
} catch ( Exception e ) {
String uuid = UUID . randomUUID ( ) . toString ( ) ;
String uuid = UUID . randomUUID ( ) . toString ( ) ;
logger . error ( uuid , e ) ;
logger . error ( uuid , e ) ;
throw new CustomException ( 10000 , trt . trt ( false , " Internal_Server_Error " ) , uuid ) ;
throw new CustomException ( 10000 , trt . trt ( false , " Internal_Server_Error " ) , uuid , false );
}
}
Map < String , Integer > result = new HashMap < > ( ) ;
Map < String , Integer > result = new HashMap < > ( ) ;
@ -1148,15 +1173,15 @@ public class MainController implements ServletContextAware {
json . put ( " error_message " , " " ) ;
json . put ( " error_message " , " " ) ;
if ( loginModel . getLogin ( ) . isEmpty ( ) )
if ( loginModel . getLogin ( ) . isEmpty ( ) )
throw new CustomException ( 10000 , trt . trt ( false , " The_login_field_is_empty " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_login_field_is_empty " ) , null , false );
if ( ! Tools . isValidEmail ( loginModel . getLogin ( ) ) )
if ( ! Tools . isValidEmail ( loginModel . getLogin ( ) ) )
throw new CustomException ( 10000 , trt . trt ( false , " The_login_field_is_incorrect " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_login_field_is_incorrect " ) , null , false );
if ( loginModel . getPassword ( ) . isEmpty ( ) )
if ( loginModel . getPassword ( ) . isEmpty ( ) )
throw new CustomException ( 10000 , trt . trt ( false , " The_password_field_is_empty " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_password_field_is_empty " ) , null , false );
if ( loginModel . getPassword ( ) . length ( ) < = 3 )
if ( loginModel . getPassword ( ) . length ( ) < = 3 )
throw new CustomException ( 10000 , trt . trt ( false , " The_password_field_is_short " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_password_field_is_short " ) , null , false );
if ( loginModel . getAppid ( ) . isEmpty ( ) )
if ( loginModel . getAppid ( ) . isEmpty ( ) )
throw new CustomException ( 10000 , trt . trt ( false , " The_application_name_field_is_empty " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_application_name_field_is_empty " ) , null , false );
String ipAddress = request . getHeader ( " X-FORWARDED-FOR " ) ; //Н е беспокойся на регистр не обращает внимания
String ipAddress = request . getHeader ( " X-FORWARDED-FOR " ) ; //Н е беспокойся на регистр не обращает внимания
if ( ipAddress = = null ) {
if ( ipAddress = = null ) {
@ -1222,19 +1247,19 @@ public class MainController implements ServletContextAware {
} catch ( DataAccessException ex ) {
} catch ( DataAccessException ex ) {
String uuid = UUID . randomUUID ( ) . toString ( ) ;
String uuid = UUID . randomUUID ( ) . toString ( ) ;
logger . error ( uuid , ex ) ;
logger . error ( uuid , ex ) ;
throw new CustomException ( 10000 , trt . trt ( false , " Error_executing_SQL_query " ) , uuid ) ;
throw new CustomException ( 10000 , trt . trt ( false , " Error_executing_SQL_query " ) , uuid , false );
}
}
if ( json = = null ) {
if ( json = = null ) {
String msg = trt . trt ( false , " Invalid_username_and_or_password " ) ;
String msg = trt . trt ( false , " Invalid_username_and_or_password " ) ;
if ( attempt_count > 0 ) {
if ( attempt_count > 0 ) {
msg = msg + " " + String . format ( trt . trt ( false , " Authorization_attempts_s_out_of_s " ) , attempt_count , attempt_limit ) ;
msg = msg + " " + String . format ( trt . trt ( false , " Authorization_attempts_s_out_of_s " ) , attempt_count , attempt_limit ) ;
}
}
throw new CustomException ( 10000 , msg , null ) ;
throw new CustomException ( 10000 , msg , null , false );
}
}
if ( json . has ( " block " ) ) {
if ( json . has ( " block " ) ) {
if ( json . getBoolean ( " block " ) )
if ( json . getBoolean ( " block " ) )
throw new CustomException ( 10006 , trt . trt ( false , " The_user_account_is_blocked " ) , null ) ;
throw new CustomException ( 10006 , trt . trt ( false , " The_user_account_is_blocked " ) , null , false );
json . remove ( " block " ) ;
json . remove ( " block " ) ;
}
}
@ -1243,13 +1268,13 @@ public class MainController implements ServletContextAware {
if ( ! json . isNull ( " secret " ) ) {
if ( ! json . isNull ( " secret " ) ) {
if ( ! Tools . isInteger ( loginModel . getTotp ( ) ) )
if ( ! Tools . isInteger ( loginModel . getTotp ( ) ) )
throw new CustomException ( 10000 , trt . trt ( false , " The_TOTP_field_is_empty " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_TOTP_field_is_empty " ) , null , false );
//Проверяю на соответствие TOTP ключа TODO потом написать поверку в функции p__Login плагином
//Проверяю на соответствие TOTP ключа TODO потом написать поверку в функции p__Login плагином
GoogleAuthenticator gAuth = new GoogleAuthenticator ( ) ;
GoogleAuthenticator gAuth = new GoogleAuthenticator ( ) ;
boolean isCodeValid = gAuth . authorize ( json . getString ( " secret " ) , Integer . valueOf ( loginModel . getTotp ( ) ) ) ;
boolean isCodeValid = gAuth . authorize ( json . getString ( " secret " ) , Integer . valueOf ( loginModel . getTotp ( ) ) ) ;
if ( ! isCodeValid ) {
if ( ! isCodeValid ) {
throw new CustomException ( 10000 , trt . trt ( false , " TOTP_key_does_not_match " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " TOTP_key_does_not_match " ) , null , false );
}
}
}
}
json . remove ( " secret " ) ;
json . remove ( " secret " ) ;
@ -1270,7 +1295,7 @@ public class MainController implements ServletContextAware {
} catch ( DataAccessException ex ) {
} catch ( DataAccessException ex ) {
String uuid = UUID . randomUUID ( ) . toString ( ) ;
String uuid = UUID . randomUUID ( ) . toString ( ) ;
logger . error ( uuid , ex ) ;
logger . error ( uuid , ex ) ;
throw new CustomException ( 10000 , trt . trt ( false , " Error_executing_SQL_query " ) , uuid ) ;
throw new CustomException ( 10000 , trt . trt ( false , " Error_executing_SQL_query " ) , uuid , false );
}
}
// Создание OTP URL
// Создание OTP URL
@ -1319,7 +1344,7 @@ public class MainController implements ServletContextAware {
if ( jwt_a . isEmpty ( ) | | countOccurrences ( jwt_a , '.' ) ! = 2 | | jwt_r . isEmpty ( ) | | countOccurrences ( jwt_r , '.' ) ! = 2 )
if ( jwt_a . isEmpty ( ) | | countOccurrences ( jwt_a , '.' ) ! = 2 | | jwt_r . isEmpty ( ) | | countOccurrences ( jwt_r , '.' ) ! = 2 )
{
{
logout ( response , request ) ;
logout ( response , request ) ;
throw new CustomException ( 10000 , trt . trt ( false , " Please_log_in " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " Please_log_in " ) , null , false );
}
}
//Разбираю токен без проверки, чтобы выбрать email
//Разбираю токен без проверки, чтобы выбрать email
@ -1341,7 +1366,7 @@ public class MainController implements ServletContextAware {
. parseClaimsJws ( jwt_r ) ;
. parseClaimsJws ( jwt_r ) ;
} catch ( Exception e ) {
} catch ( Exception e ) {
logout ( response , request ) ;
logout ( response , request ) ;
throw new CustomException ( 10000 , Arrays . asList ( trt . trt ( false , " Please_log_in " ) , trt . trt ( false , " JWT_token_verification_error " ) ) , null ) ;
throw new CustomException ( 10000 , Arrays . asList ( trt . trt ( false , " Please_log_in " ) , trt . trt ( false , " JWT_token_verification_error " ) ) , null , false );
}
}
//Для обнаружения попытки взлома проверяю чтобы подпись токена доступа совпадала с тем что записано в токете обновления
//Для обнаружения попытки взлома проверяю чтобы подпись токена доступа совпадала с тем что записано в токете обновления
@ -1568,26 +1593,26 @@ public class MainController implements ServletContextAware {
json . put ( " error_message " , " " ) ;
json . put ( " error_message " , " " ) ;
if ( update = = null )
if ( update = = null )
throw new CustomException ( 10000 , trt . trt ( false , " Please_send_a_valid_JSON_string_in_your_request " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " Please_send_a_valid_JSON_string_in_your_request " ) , null , false );
if ( update . getLogin ( ) . isEmpty ( ) )
if ( update . getLogin ( ) . isEmpty ( ) )
throw new CustomException ( 10000 , trt . trt ( false , " The_login_field_is_empty " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_login_field_is_empty " ) , null , false );
if ( ! Tools . isValidEmail ( update . getLogin ( ) ) )
if ( ! Tools . isValidEmail ( update . getLogin ( ) ) )
throw new CustomException ( 10000 , trt . trt ( false , " The_email_field_is_incorrect " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_email_field_is_incorrect " ) , null , false );
if ( update . getPassword ( ) . isEmpty ( ) )
if ( update . getPassword ( ) . isEmpty ( ) )
throw new CustomException ( 10000 , trt . trt ( false , " The_password_field_is_empty " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_password_field_is_empty " ) , null , false );
if ( update . getPasswordNew ( ) . isEmpty ( ) )
if ( update . getPasswordNew ( ) . isEmpty ( ) )
throw new CustomException ( 10000 , trt . trt ( false , " The_new_password_field_is_empty " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_new_password_field_is_empty " ) , null , false );
if ( ! Pattern . compile ( " [0-9] " ) . matcher ( update . getPasswordNew ( ) ) . find ( ) )
if ( ! Pattern . compile ( " [0-9] " ) . matcher ( update . getPasswordNew ( ) ) . find ( ) )
throw new CustomException ( 10000 , trt . trt ( false , " The_password_is_missing_a_number " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_password_is_missing_a_number " ) , null , false );
if ( ! Pattern . compile ( " [a-z] " ) . matcher ( update . getPasswordNew ( ) ) . find ( ) )
if ( ! Pattern . compile ( " [a-z] " ) . matcher ( update . getPasswordNew ( ) ) . find ( ) )
throw new CustomException ( 10000 , trt . trt ( false , " The_password_is_missing_a_small_Latin_letter " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_password_is_missing_a_small_Latin_letter " ) , null , false );
if ( ! Pattern . compile ( " [A-Z] " ) . matcher ( update . getPasswordNew ( ) ) . find ( ) )
if ( ! Pattern . compile ( " [A-Z] " ) . matcher ( update . getPasswordNew ( ) ) . find ( ) )
throw new CustomException ( 10000 , trt . trt ( false , " The_password_is_missing_a_big_Latin_letter " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_password_is_missing_a_big_Latin_letter " ) , null , false );
if ( ! Pattern . compile ( " [_!@#$%^&*] " ) . matcher ( update . getPasswordNew ( ) ) . find ( ) )
if ( ! Pattern . compile ( " [_!@#$%^&*] " ) . matcher ( update . getPasswordNew ( ) ) . find ( ) )
throw new CustomException ( 10000 , trt . trt ( false , " The_password_is_missing_a_special_letter " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_password_is_missing_a_special_letter " ) , null , false );
if ( update . getPasswordNew ( ) . length ( ) < 6 )
if ( update . getPasswordNew ( ) . length ( ) < 6 )
throw new CustomException ( 10000 , trt . trt ( false , " The_password_is_less_than_six_characters " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " The_password_is_less_than_six_characters " ) , null , false );
//Проверяем попытки смены пароля (сохраение попыток в функции логина)
//Проверяем попытки смены пароля (сохраение попыток в функции логина)
String ipAddress = request . getHeader ( " X-FORWARDED-FOR " ) ;
String ipAddress = request . getHeader ( " X-FORWARDED-FOR " ) ;
@ -1629,7 +1654,7 @@ public class MainController implements ServletContextAware {
rows = new JSONObject ( ret . get ( i ) ) ;
rows = new JSONObject ( ret . get ( i ) ) ;
}
}
if ( rows = = null )
if ( rows = = null )
throw new CustomException ( 10000 , trt . trt ( false , " Invalid_username_and_or_password " ) , null ) ;
throw new CustomException ( 10000 , trt . trt ( false , " Invalid_username_and_or_password " ) , null , false );
//Обновляю пароль
//Обновляю пароль
sql = " update main._users set password=crypt(:password_new, gen_salt('bf')),password_new = null,expiration=now()+INTERVAL '1 year' where password=crypt(:password, password) and email=:email " ;
sql = " update main._users set password=crypt(:password_new, gen_salt('bf')),password_new = null,expiration=now()+INTERVAL '1 year' where password=crypt(:password, password) and email=:email " ;
@ -1685,7 +1710,7 @@ public class MainController implements ServletContextAware {
Translation trt = new Translation ( language_id , jdbcTemplate ) ;
Translation trt = new Translation ( language_id , jdbcTemplate ) ;
try {
try {
if ( authentication = = null | | ! authentication . isAuthenticated ( ) ) {
if ( authentication = = null | | ! authentication . isAuthenticated ( ) ) {
throw new CustomException ( 10000 , Collections . singletonList ( trt . trt ( false , " Please_log_in " ) ) , null ) ;
throw new CustomException ( 10000 , Collections . singletonList ( trt . trt ( false , " Please_log_in " ) ) , null , false );
}
}
UserDetails userDetails = ( UserDetails ) authentication . getPrincipal ( ) ;
UserDetails userDetails = ( UserDetails ) authentication . getPrincipal ( ) ;
@ -1697,9 +1722,9 @@ public class MainController implements ServletContextAware {
if ( data ! = null ) {
if ( data ! = null ) {
logout ( response , request ) ;
logout ( response , request ) ;
if ( data . equals ( " repeat " ) ) {
if ( data . equals ( " repeat " ) ) {
throw new CustomException ( 10000 , Arrays . asList ( trt . trt ( false , " Please_log_in " ) , trt . trt ( false , " Reauthorization_detected_if_it_is_not_you_please_change_your_password " ) ) , null ) ;
throw new CustomException ( 10000 , Arrays . asList ( trt . trt ( false , " Please_log_in " ) , trt . trt ( false , " Reauthorization_detected_if_it_is_not_you_please_change_your_password " ) ) , null , false );
} else {
} else {
throw new CustomException ( 10000 , Arrays . asList ( trt . trt ( false , " Please_log_in " ) , trt . trt ( false , " Your_authorization_token_is_not_valid " ) ) , null ) ;
throw new CustomException ( 10000 , Arrays . asList ( trt . trt ( false , " Please_log_in " ) , trt . trt ( false , " Your_authorization_token_is_not_valid " ) ) , null , false );
}
}
}
}
}
}