package com.railway.framework.security.handle;

import com.alibaba.fastjson.JSON;
import com.railway.common.constant.Constants;
import com.railway.common.constant.HttpStatus;
import com.railway.common.core.domain.AjaxResult;
import com.railway.common.core.domain.model.LoginUser;
import com.railway.common.utils.ServletUtils;
import com.railway.common.utils.StringUtils;
import com.railway.framework.manager.AsyncManager;
import com.railway.framework.manager.factory.AsyncFactory;
import com.railway.framework.web.service.TokenService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

/**
 * 自定义退出处理类 返回成功
 *
 * @author railway
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

  private final TokenService tokenService;

  public LogoutSuccessHandlerImpl(TokenService tokenService) {
    this.tokenService = tokenService;
  }

  /**
   * 退出处理
   */
  @Override
  public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
      Authentication authentication) {
    LoginUser loginUser = tokenService.getLoginUser(request);
    if (StringUtils.isNotNull(loginUser)) {
      String userName = loginUser.getUsername();
      // 删除用户缓存记录
      tokenService.delLoginUser(loginUser.getToken());
      // 记录用户退出日志
      AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
    }
    ServletUtils.renderString(response,
        JSON.toJSONString(AjaxResult.error(HttpStatus.SUCCESS, "退出成功")));
  }
}
