org.homiefund.test.config.SecurityConextPrincipalFactory.java Source code

Java tutorial

Introduction

Here is the source code for org.homiefund.test.config.SecurityConextPrincipalFactory.java

Source

/**
 * Copyright  2016 REPLACE ME OWNER (REPLACE ME YEAR)
 *
 * 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 org.homiefund.test.config;

import lombok.extern.log4j.Log4j2;
import org.homiefund.api.dto.HomeDTO;
import org.homiefund.api.dto.UserDTO;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.context.support.WithSecurityContextFactory;

import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by Dominik Szalai - emptulik at gmail.com on 30.9.2016.
 */
@Log4j2
public class SecurityConextPrincipalFactory implements WithSecurityContextFactory<WithUser>, EnvironmentAware {
    private Environment environment;

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    @Override
    public SecurityContext createSecurityContext(WithUser withUser) {
        SecurityContext context = SecurityContextHolder.createEmptyContext();

        UserDTO user = new UserDTO();
        user.setId(withUser.id());
        user.setHomes(Stream.of(withUser.homes()).map(h -> {
            HomeDTO home = new HomeDTO();
            home.setId(h.id());
            return home;
        }).collect(Collectors.toList()));

        Authentication auth = new UsernamePasswordAuthenticationToken(user, user.getPassword(),
                user.getAuthorities());

        context.setAuthentication(auth);

        return context;
    }
}