1
1
package com .example .busan .auth .domain ;
2
2
3
+ import com .example .busan .auth .dto .Authentication ;
4
+ import com .example .busan .auth .exception .UnauthorizedException ;
5
+ import jakarta .servlet .http .Cookie ;
3
6
import jakarta .servlet .http .HttpServletRequest ;
7
+ import jakarta .servlet .http .HttpServletResponse ;
8
+ import jakarta .servlet .http .HttpSession ;
4
9
import org .springframework .stereotype .Component ;
5
10
6
11
import java .util .Arrays ;
@@ -10,12 +15,56 @@ public class AutoLoginManager {
10
15
11
16
public static final String AUTO_LOGIN_COOKIE_NAME = "AUTO" ;
12
17
18
+ private final AutoLoginRepository autoLoginRepository ;
19
+
20
+ public AutoLoginManager (AutoLoginRepository autoLoginRepository ) {
21
+ this .autoLoginRepository = autoLoginRepository ;
22
+ }
23
+
13
24
public boolean isAuto (final HttpServletRequest request ) {
14
25
if (request == null ) {
15
26
return false ;
16
27
}
17
28
18
29
return Arrays .stream (request .getCookies ())
19
- .anyMatch (cookie -> cookie .getName ().equals ("AUTO" ));
30
+ .anyMatch (cookie -> cookie .getName ().equals (AUTO_LOGIN_COOKIE_NAME ));
31
+ }
32
+
33
+ public void setAutoCookie (final HttpSession httpSession ,
34
+ final HttpServletResponse response ,
35
+ final Authentication authentication ) {
36
+ final String id = httpSession .getId ();
37
+
38
+ autoLoginRepository .save (new AutoLogin (id , authentication ));
39
+
40
+ final Cookie cookie = new Cookie (AUTO_LOGIN_COOKIE_NAME , id );
41
+ cookie .setPath ("/" );
42
+ cookie .setMaxAge (Integer .MAX_VALUE );
43
+ response .addCookie (cookie );
44
+ }
45
+
46
+ public Authentication getAuthentication (final HttpServletRequest request ) {
47
+ final Cookie autoLoggedInCookie = getAutoLoggedInCookie (request );
48
+
49
+ final String id = autoLoggedInCookie .getValue ();
50
+ return autoLoginRepository .findById (id )
51
+ .orElseThrow (UnauthorizedException ::new )
52
+ .getAuthentication ();
53
+ }
54
+
55
+ private Cookie getAutoLoggedInCookie (final HttpServletRequest request ) {
56
+ return Arrays .stream (request .getCookies ())
57
+ .filter (cookie -> cookie .getName ().equals (AUTO_LOGIN_COOKIE_NAME ))
58
+ .findAny ()
59
+ .orElseThrow (UnauthorizedException ::new );
60
+ }
61
+
62
+ public void removeAutoLogin (final HttpServletRequest request ,
63
+ final HttpServletResponse response ) {
64
+ final Cookie autoLoggedInCookie = getAutoLoggedInCookie (request );
65
+ autoLoggedInCookie .setMaxAge (0 );
66
+ response .addCookie (autoLoggedInCookie );
67
+
68
+ autoLoginRepository .deleteById (autoLoggedInCookie .getValue ());
20
69
}
21
70
}
0 commit comments