/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.csp.sentinel.dashboard.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.csp.sentinel.dashboard.auth.AuthService;
import com.alibaba.csp.sentinel.dashboard.auth.SimpleWebAuthServiceImpl;
import com.alibaba.csp.sentinel.dashboard.config.DashboardConfig;
import com.alibaba.csp.sentinel.dashboard.domain.Result;
import com.google.common.net.HttpHeaders;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CacheConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.core.util.SpringContextHolder;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.event.LogoutSuccessEvent;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author cdfive
 * @since 1.6.0
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/auth")
public class AuthController {

	private final ClientDetailsService clientDetailsService;

	private final TokenStore tokenStore;

	private final RedisTemplate redisTemplate;

	private final CacheManager cacheManager;

	private static final Logger LOGGER = LoggerFactory.getLogger(AuthController.class);

	@Value("${auth.username:sentinel}")
	private String authUsername;

	@Value("${auth.password:sentinel}")
	private String authPassword;

	@Autowired
	private AuthService<HttpServletRequest> authService;

	@PostMapping("/login")
	public Result<AuthService.AuthUser> login(HttpServletRequest request, String username, String password) {
		if (StringUtils.isNotBlank(DashboardConfig.getAuthUsername())) {
			authUsername = DashboardConfig.getAuthUsername();
		}

		if (StringUtils.isNotBlank(DashboardConfig.getAuthPassword())) {
			authPassword = DashboardConfig.getAuthPassword();
		}

		/*
		 * If auth.username or auth.password is blank(set in application.properties or VM
		 * arguments), auth will pass, as the front side validate the input which can't be
		 * blank, so user can input any username or password(both are not blank) to login
		 * in that case.
		 */
		if (StringUtils.isNotBlank(authUsername) && !authUsername.equals(username)
				|| StringUtils.isNotBlank(authPassword) && !authPassword.equals(password)) {
			LOGGER.error("Login failed: Invalid username or password, username=" + username);
			return Result.ofFail(-1, "Invalid username or password");
		}

		AuthService.AuthUser authUser = new SimpleWebAuthServiceImpl.SimpleWebAuthUserImpl(username);
		request.getSession().setAttribute(SimpleWebAuthServiceImpl.WEB_SESSION_KEY, authUser);
		return Result.ofSuccess(authUser);
	}

	@PostMapping(value = "/logout")
	public Result<?> logout(HttpServletRequest request) {
		request.getSession().invalidate();
		return Result.ofSuccess(null);
	}

	@PostMapping(value = "/check")
	public Result<?> check(HttpServletRequest request) {
		AuthService.AuthUser authUser = authService.getAuthUser(request);
		if (authUser == null) {
			return Result.ofFail(-1, "Not logged in");
		}
		return Result.ofSuccess(authUser);
	}

/*	*//**
	 * 退出并删除token
	 * @param authHeader Authorization
	 *//*
	@DeleteMapping("/logout")
	public R<Boolean> logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader) {
		if (StrUtil.isBlank(authHeader)) {
			return R.ok();
		}

		String tokenValue = authHeader.replace(OAuth2AccessToken.BEARER_TYPE, StrUtil.EMPTY).trim();
		return removeToken(tokenValue);
	}
	*//**
	 * 令牌管理调用
	 * @param token token
	 *//*
	@DeleteMapping("/{token}")
	public R<Boolean> removeToken(@PathVariable("token") String token) {
		OAuth2AccessToken accessToken = tokenStore.readAccessToken(token);
		if (accessToken == null || StrUtil.isBlank(accessToken.getValue())) {
			return R.ok();
		}

		OAuth2Authentication auth2Authentication = tokenStore.readAuthentication(accessToken);
		// 清空用户信息
		cacheManager.getCache(CacheConstants.USER_DETAILS).evict(auth2Authentication.getName());

		// 清空access token
		tokenStore.removeAccessToken(accessToken);

		// 清空 refresh token
		OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
		tokenStore.removeRefreshToken(refreshToken);

		// 处理自定义退出事件，保存相关日志
		SpringContextHolder.publishEvent(new LogoutSuccessEvent(auth2Authentication));
		return R.ok();
	}*/

}
