package com.lanyuanxiaoyao.service.gateway.configuration;

import com.lanyuanxiaoyao.service.configuration.SecurityProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.core.userdetails.MapReactiveUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.server.SecurityWebFilterChain;

/**
 * web security
 *
 * @author lanyuanxiaoyao
 * @date 2024-01-15
 */
@Configuration
@EnableWebFluxSecurity
public class SecurityConfiguration {
    @Bean
    public SecurityWebFilterChain SecurityWebFilterChain(ServerHttpSecurity http) {
        return http.authorizeExchange()
                .pathMatchers("/actuator")
                .authenticated()
                .anyExchange()
                .permitAll()
                .and()
                .httpBasic()
                .and()
                .csrf()
                .disable()
                .build();
    }

    @Bean
    public MapReactiveUserDetailsService userDetailsService(SecurityProperties securityProperties) {
        UserDetails user = User.builder()
                .username(securityProperties.getUsername())
                .password("{noop}" + securityProperties.getDarkcode())
                .authorities(securityProperties.getAuthority())
                .build();
        return new MapReactiveUserDetailsService(user);
    }
}
