package com.example.config;

import com.example.frame.utils.MD5Util;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import com.example.frame.base.Token;
import com.example.frame.utils.CookieUtil;
import com.example.frame.utils.LocalData;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Value("${web.url.auth.excluded}")
    private String[] excluded;
    @Value("${spring.mvc.static-path-pattern}")
    private String[] staticPath;
    @Value("${admin.username}")
    private String username;
    @Value("${admin.password}")
    private String password;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()
                .antMatchers(staticPath).permitAll()
                .antMatchers(excluded).permitAll()
                .anyRequest().access("@Authorization.hasPermission(request,authentication)")
                .and().cors()
                .and().headers().frameOptions().disable()
                .and().csrf().disable();
    }

    /**
     * 此方法不要删除 用于屏蔽默认用户密码生成
     * <p>
     * 例如 Using generated security password: f6b42a66-71b1-4c31-b6a8-942838c81408
     *
     * @return
     * @throws Exception
     */
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean("Authorization")
    public Object getAuthorization() {
        return new Object() {
            public boolean hasPermission(HttpServletRequest request, Authentication authentication) {

                // 获取Token
                String token = request.getParameter("token");
                if (token == null || token.isEmpty()) {
                    token = CookieUtil.getCookieValue(request.getCookies(), "token");
                }

                String yyyyMMdd = new SimpleDateFormat("yyyyMMdd").format(new Date());
                String encode = MD5Util.encode(yyyyMMdd + username + password);

                if (token == null) {
                    LocalData.setToken(LocalData.getTempToken());
                } else if (!encode.equals(token)) {
                    LocalData.setToken(LocalData.getTempToken());
                } else {
                    Token token1 = new Token();
                    token1.setId(1L);
                    token1.setUserId(1L);
                    token1.setUserName(username);
                    token1.putResource("/");
                    token1.putResource("/mapping.htm");
                    token1.putResource("/sse/.*");
                    token1.putResource("/ajax");
                    token1.putResource("ajax.login");
                    token1.putResource("nginx.start");
                    token1.putResource("nginx.stop");
                    token1.putResource("nginx.reload");
                    token1.putResource("ajax.admin.mapping.create");
                    token1.putResource("ajax.admin.mapping.delete");
                    token1.putResource("ajax.admin.mapping.update");
                    token1.putResource("ajax.admin.service.load");
                    token1.putResource("ajax.admin.config.flush");
                    LocalData.setToken(token1);
                }
                String servletPath = request.getServletPath();
                // 授权
                Token token_ = LocalData.getToken();
                if (token_.hasResource(request.getServletPath())) {
                    return true;
                }

//                try {
//                    LocalData.getResponse().sendRedirect("/login.htm");
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }

                return false;
            }
        };
    }

}
