/**
 *
 */
package org.jenkinsci.plugins;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.userdetails.User;
import org.acegisecurity.userdetails.UserDetails;
import org.kohsuke.github.GHUser;

import javax.annotation.Nonnull;
import java.io.IOException;

/**
 * @author Mike
 *
 */
@SuppressFBWarnings("EQ_DOESNT_OVERRIDE_EQUALS")
public class GithubOAuthUserDetails extends User implements UserDetails {

    private static final long serialVersionUID = 1L;

    private final GithubAuthenticationToken authenticationToken;

    public GithubOAuthUserDetails(@Nonnull String login, @Nonnull GrantedAuthority[] authorities) {
        super(login, "", true, true, true, true, authorities);
        this.authenticationToken = null;
    }

    public GithubOAuthUserDetails(@Nonnull String login, @Nonnull GithubAuthenticationToken authenticationToken) {
        super(login, "", true, true, true, true, null);
        this.authenticationToken = authenticationToken;
    }

    @Override
    public GrantedAuthority[] getAuthorities() {
        if (super.getAuthorities() == null) {
            try {
                GHUser user = authenticationToken.loadUser(getUsername());
                setAuthorities(authenticationToken.getGrantedAuthorities(user));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return super.getAuthorities();
    }
}

@@ -533,16 +533,60 @@
  = 1L;%0A%0A
+    private boolean hasGrantedAuthorities;%0A%0A
     priv
@@ -642,16 +642,16 @@
 nToken;%0A
-
 %0A    pub
@@ -847,16 +847,59 @@
 = null;%0A
+        this.hasGrantedAuthorities = true;%0A
     %7D%0A%0A 
@@ -1062,19 +1062,38 @@
  true, n
-ull
+ew GrantedAuthority%5B0%5D
 );%0A     
@@ -1143,16 +1143,60 @@
 nToken;%0A
+        this.hasGrantedAuthorities = false;%0A
     %7D%0A%0A 
@@ -1269,25 +1269,27 @@
     if (
-super.get
+!hasGranted
 Authorit
@@ -1295,18 +1295,8 @@
 ties
-() == null
 ) %7B%0A

Fix for "java.lang.IllegalArgumentException: Cannot pass a null GrantedAuthority array"