Skip to content

Commit

Permalink
feat: user session login
Browse files Browse the repository at this point in the history
  • Loading branch information
dkz359 committed Nov 16, 2024
1 parent e46a260 commit cea8aa4
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,44 @@
import com.dukz.authdemo.session.model.UserDto;
import com.dukz.authdemo.session.service.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Objects;

@RestController
public class LoginController {

@Autowired
private AuthenticationService authenticationService;

@PostMapping(value = "/login", produces = "text/plain;charset=utf-8")
public String authentication(AuthenticationRequest authenticationRequest){
public String authentication(AuthenticationRequest authenticationRequest, HttpSession session){
UserDto userDto = authenticationService.authentication(authenticationRequest);
// set session
session.setAttribute(UserDto.USER_SESSION_KEY, userDto);
return userDto.getFullname() + " login success";
}

@GetMapping(value = "/logout", produces = "text/plain;charset=utf-8")
public String logout(HttpSession session){
session.invalidate();
return "logout success";
}
@GetMapping(value = "/r/r1", produces = "text/plain;charset=utf-8")
public String readResource(HttpSession session){
String fullname = "";
Object obj = session.getAttribute(UserDto.USER_SESSION_KEY);
if(Objects.isNull(obj)){
fullname = "匿名";
}else {
UserDto user = (UserDto) obj;
fullname = user.getFullname();
}
return fullname + "访问资源r1";
}


}
1 change: 1 addition & 0 deletions src/main/java/com/dukz/authdemo/session/model/UserDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
@AllArgsConstructor
@NoArgsConstructor
public class UserDto {
public static final String USER_SESSION_KEY = "_user";
private Integer id;
private String username;
private String password;
Expand Down

0 comments on commit cea8aa4

Please sign in to comment.