dubbo.spring.javaconfig.CurrentUserFilter.java Source code

Java tutorial

Introduction

Here is the source code for dubbo.spring.javaconfig.CurrentUserFilter.java

Source

/*
 * Copyright 2016-2017 the original author or authors.
 *
 * 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 dubbo.spring.javaconfig;

import com.alibaba.dubbo.rpc.Filter;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.dubbo.rpc.RpcException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.wiiyaya.framework.common.model.LoginUserInfo;
import org.wiiyaya.framework.common.model.SimpleGrantedAuthority;
import org.wiiyaya.framework.common.utils.StringUtilsPlus;
import org.wiiyaya.provider.main.entity.BackendUser;
import org.wiiyaya.provider.main.repository.BackendUserRepo;

import java.util.ArrayList;

/**
 * <p></p>
 *
 * <p>??</p>
 *
 * <p></p>
 *
 * @author wiiyaya
 *
 */
public class CurrentUserFilter implements Filter {

    private BackendUserRepo backendUserRepo;

    //dubbosetter?  
    public void setBackendUserRepo(BackendUserRepo backendUserRepo) {
        this.backendUserRepo = backendUserRepo;
    }

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String currentUserId = RpcContext.getContext().getAttachment("currentUserId");
        if (StringUtilsPlus.isNotEmpty(currentUserId)) {
            BackendUser user = backendUserRepo.findOne(Long.parseLong(currentUserId));
            LoginUserInfo currentUser = new LoginUserInfo();
            currentUser.setId(Long.parseLong(currentUserId));
            Authentication auth = new UsernamePasswordAuthenticationToken(currentUser, StringUtilsPlus.EMPTY,
                    new ArrayList<SimpleGrantedAuthority>());
            SecurityContextHolder.getContext().setAuthentication(auth);
        }
        return invoker.invoke(invocation);
    }

}