1010import uz .server .repository .TunnelRepository ;
1111
1212import java .security .SecureRandom ;
13+ import java .util .Objects ;
1314import java .util .Optional ;
1415
1516@ Service
1819public class TunnelService {
1920 private final TunnelRepository repo ;
2021
21- public String create (String sessionId , User user ) {
22+ public String create (String sessionId , User user , String customSubdomain ) {
2223 log .info ("Creating tunnel: userId={}" , user .getId ());
2324 Integer count = repo .countByUser (user );
2425
@@ -27,9 +28,14 @@ public String create(String sessionId, User user) {
2728 throw new BaseException ("You can't create more than 3 tunnels!" );
2829 }
2930
31+ if (customSubdomain != null && repo .existsBySubdomain (customSubdomain )){
32+ log .error ("Subdomain already exists: subdomain={}" , customSubdomain );
33+ throw new BaseException ("Subdomain already exists!" );
34+ }
35+
3036 Tunnel save = repo .save (Tunnel .builder ()
3137 .sessionId (sessionId )
32- .subdomain (generateUniqueString ())
38+ .subdomain (Objects . requireNonNullElse ( customSubdomain , generateUniqueString () ))
3339 .user (user )
3440 .build ());
3541
@@ -44,10 +50,12 @@ private String generateUniqueString() {
4450 SecureRandom RANDOM = new SecureRandom ();
4551
4652 sb .append (timestamp );
53+
4754 for (int i = 0 ; i < 8 ; i ++) {
4855 String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" ;
4956 sb .append (CHARACTERS .charAt (RANDOM .nextInt (CHARACTERS .length ())));
5057 }
58+
5159 return sb .toString ();
5260 }
5361
0 commit comments