/*
 * Wegas
 * http://wegas.albasim.ch
 *
 * Copyright (c) 2013-2018 School of Business and Engineering Vaud, Comem, MEI
 * Licensed under the MIT License
 */
package com.wegas.core.security.aai;

import com.wegas.core.exception.internal.WegasNoResultException;
import com.wegas.core.security.ejb.AccountFacade;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.LoggerFactory;


/**
 * Wegas
 * http://wegas.albasim.ch
 * <p>
 * Copyright (c) AlbaSim, School of Business and Engineering of Western Switzerland
 * Licensed under the MIT License
 * Created by jarle.hulaas@heig-vd.ch on 07.03.2017.
 */
public class AaiRealm extends AuthorizingRealm {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AaiRealm.class);

    public AaiRealm() {
        setName("AaiRealm");                //This name must match the name in the User class's getPrincipals() method
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof AaiToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //Effective authorisations are fetched by JpaRealm in all case
        return new SimpleAuthorizationInfo();
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        AaiToken token = (AaiToken) authcToken;
        //Long userid = (Long)token.getPrincipal();
        AaiUserDetails userDetails = token.getUserDetails();
        AccountFacade accountFacade = AccountFacade.lookup();
        try {
            AaiAccount account = accountFacade.findByPersistentId(userDetails.getPersistentId());
            AaiAuthenticationInfo info = new AaiAuthenticationInfo(account.getId(), userDetails, getName());
            return info;
        } catch (WegasNoResultException ex) {
            logger.error("Unable to find token", ex);
            return null;
        }
    }
}

@@ -190,16 +190,99 @@
 y.aai;%0A%0A
+import com.wegas.core.ejb.RequestFacade;%0Aimport com.wegas.core.ejb.RequestManager;%0A
 import c
@@ -1893,13 +1893,130 @@
     
-try %7B
+RequestManager requestManager = RequestFacade.lookup().getRequestManager();%0A        try %7B%0A            requestManager.su();
 %0A   
@@ -2369,16 +2369,76 @@
 n null;%0A
+        %7D finally %7B%0A            requestManager.releaseSu();%0A
         

fix shadow related issue