<%#
 Copyright 2013-2024 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 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

      https://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 <%= packageName %>.security;

import <%= user.entityAbsoluteClass %>;
<%_ if (ormTool === 'mybatis') { _%>
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diboot.core.binding.Binder;
<%_ } _%>
<%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j) { _%>
import <%= packageName %>.domain.Authority;
<%_ } _%>
import <%= packageName %>.repository.UserRepository;
import org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
<%_ if (reactive) { _%>
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
<%_ } _%>
import org.springframework.security.core.userdetails.UserDetails;
<%_ if (!reactive) { _%>
import org.springframework.security.core.userdetails.UserDetailsService;
<%_ } _%>
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
<%_ if (databaseTypeSql) { _%>
import org.springframework.transaction.annotation.Transactional;
<%_ } _%>
<%_ if (reactive) { _%>
import reactor.core.publisher.Mono;
<%_ } _%>

import java.util.*;
<%_ if (javaVersion === '8') { _%>
import java.util.stream.Collectors;
<%_ } _%>

/**
 * Authenticate a user from the database.
 */
@Component("userDetailsService")
public class DomainUserDetailsService implements <% if (reactive) { %>Reactive<% } %>UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(DomainUserDetailsService.class);

    private final UserRepository userRepository;

    public DomainUserDetailsService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
<%_ if (databaseTypeSql && ormTool !== 'hibernate') { _%>
    @Transactional(readOnly = true)
<%_ } _%>
    public <% if (reactive) { %>Mono<UserDetails> findByUsername<% } else { %>UserDetails loadUserByUsername<% } %>(final String login) {
        log.debug("Authenticating {}", login);

        if (new EmailValidator().isValid(login, null)) {
    <%_ if (ormTool === 'hibernate') { _%>
            return userRepository.<% if (databaseTypeSql) { %>findOneWithAuthoritiesByEmailIgnoreCase<% } else { %>findOneByEmailIgnoreCase<% } %>(login)
    <%_ } else { _%>
            this.userRepository.findOneByEmailIgnoreCase(login)
                .map(user -> {
                    Binder.bindRelations(user);
                    return user;
                })
    <%_ } _%>
<%_ if (reactive) { _%>
                .switchIfEmpty(Mono.error(new UsernameNotFoundException("User with email " + login + " was not found in the database")))
<%_ } _%>
                .map(user -> createSpringSecurityUser(login, user))<% if (!reactive) { %>
                .orElseThrow(() -> new UsernameNotFoundException("User with email " + login + " was not found in the database"))<% } %>;
        }

        String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
    <%_ if (ormTool === 'hibernate') { _%>
        return userRepository.findOne<% if (databaseTypeSql) { %>WithAuthorities<% } %>ByLogin(lowercaseLogin)
    <%_ } else { _%>
    return this.userRepository.findOneByLogin(lowercaseLogin)
            .map(user -> {
                Binder.bindRelations(user);
                return user;
            })
    <%_ } _%>
<%_ if (reactive) { _%>
            .switchIfEmpty(Mono.error(new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database")))
<%_ } _%>
            .map(user -> createSpringSecurityUser(lowercaseLogin, user))<% if (!reactive) { %>
            .orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database"))<% } %>;

    }

    private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, <%= persistClass %> user) {
        if (!user.getActivated()) {
            throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
        }
        List<SimpleGrantedAuthority> grantedAuthorities = user.getAuthorities().stream()<% if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j) { %>
            .map(Authority::getCode)<% } %>
            .map(SimpleGrantedAuthority::new)
            <% if (javaVersion !== '8') { %>.toList();<% } else { %>.collect(Collectors.toList());<% } %>
        return new MyUserDetails(user.getLogin(),
            user.getPassword(),
            grantedAuthorities, user.getId());
    }
}
