package com.atlassian.stash.internal.user;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.security.access.expression.SecurityExpressionHandler;
import org.springframework.security.access.expression.SecurityExpressionRoot;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.FilterInvocation;

public class ExtendedWebSecurityExpressionHandler implements SecurityExpressionHandler<FilterInvocation> {

    private final AuthenticationTrustResolver trustResolver = new ExtendedAuthenticationTrustResolver();
    private final ExpressionParser expressionParser = new SpelExpressionParser();

    private InternalPermissionService permissionService;

    @Override
    public EvaluationContext createEvaluationContext(Authentication authentication, FilterInvocation fi) {
        StandardEvaluationContext ctx = new StandardEvaluationContext();
        SecurityExpressionRoot root = new ExtendedWebSecurityExpressionRoot(authentication, fi, permissionService);
        root.setTrustResolver(trustResolver);
        ctx.setRootObject(root);

        return ctx;
    }

    @Override
    public ExpressionParser getExpressionParser() {
        return expressionParser;
    }

    public void setPermissionService(InternalPermissionService permissionService) {
        this.permissionService = permissionService;
    }
}
