package com.atlassian.stash.internal.user;

import com.atlassian.bitbucket.permission.Permission;
import com.google.common.base.Preconditions;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.expression.WebSecurityExpressionRoot;


public class ExtendedWebSecurityExpressionRoot extends WebSecurityExpressionRoot {

    private final InternalPermissionService permissionService;

    public ExtendedWebSecurityExpressionRoot(Authentication a, FilterInvocation fi,
                                             InternalPermissionService permissionService) {
        super(a, fi);
        this.permissionService = permissionService;        
    }
    
    public boolean hasGlobalPermission(String permission) {        
        Permission requestedPerm = Permission.valueOf(permission);
        Preconditions.checkArgument(requestedPerm.isGlobal());
        return permissionService.hasGlobalPermission(resolveAuthenticationToken(), requestedPerm);
    }

    private StashUserAuthenticationToken resolveAuthenticationToken() {
        if (authentication instanceof StashUserAuthenticationToken) {
            return (StashUserAuthenticationToken) authentication;
        }
        return null;
    }

}
