package com.izouma.awesomeadmin.activiti;

import com.izouma.awesomeadmin.model.UserInfo;
import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class CustomAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private IdentityService identityService;

    public CustomAuthenticationProvider() {
    }

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String name = authentication.getName();
        String password = authentication.getCredentials().toString();
        boolean authenticated = this.identityService.checkPassword(name, password);

        UserInfo userInfo = null;
        try {
            userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (userInfo == null) {

        }

        if (userInfo == null) {
            throw new BadCredentialsException("Authentication failed for this username and password");
        } else {
            this.identityService.setAuthenticatedUserId(userInfo.getId().toString());
        }


        if (!authenticated) {
            throw new BadCredentialsException("Authentication failed for this username and password");
        } else {
            List<Group> groups = this.identityService.createGroupQuery().groupMember(name).list();
            Collection<GrantedAuthority> grantedAuthorities = new ArrayList();
            Iterator var7 = groups.iterator();

            while (var7.hasNext()) {
                Group group = (Group) var7.next();
                grantedAuthorities.add(new SimpleGrantedAuthority(group.getId()));
            }

            this.identityService.setAuthenticatedUserId(name);
            return new UsernamePasswordAuthenticationToken(name, password, grantedAuthorities);
        }
    }

    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}