/*******************************************************************************
 * Copyright 2015 Fondazione Bruno Kessler
 * 
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 * 
 *        http://www.apache.org/licenses/LICENSE-2.0
 * 
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 ******************************************************************************/

package it.smartcommunitylab.aac.oauth;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.TokenRequest;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import it.smartcommunitylab.aac.manager.ProviderServiceAdapter;
import it.smartcommunitylab.aac.model.User;

/**
 * @author raman
 *
 */
public class NativeTokenGranter extends AbstractTokenGranter {

	private ProviderServiceAdapter providerService;

	public NativeTokenGranter(ProviderServiceAdapter providerService, AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService,
			OAuth2RequestFactory requestFactory, String grantType) {
		super(tokenServices, clientDetailsService, requestFactory, grantType);
		this.providerService = providerService;
	}

	protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
		Map<String, String> params = tokenRequest.getRequestParameters();
		String authority = params.get("authority");
		String token = params.get("token");
		if (StringUtils.isEmpty(authority) || StringUtils.isEmpty(token)) {
			throw new InvalidGrantException("Missing token or authority parameters");
		}
				
		User nativeUser = providerService.updateNativeUser(authority, token, params);
		
		List<GrantedAuthority> list = Collections.<GrantedAuthority> singletonList(new SimpleGrantedAuthority("ROLE_USER"));

		Authentication user = new UsernamePasswordAuthenticationToken(nativeUser.getId().toString(), null, list);
		
		tokenRequest.setScope(providerService.userScopes(nativeUser, tokenRequest.getScope(), true));
		
		OAuth2Authentication authentication = new OAuth2Authentication(tokenRequest.createOAuth2Request(client), user);
		return authentication;
	}
}

@@ -1000,32 +1000,24 @@
 ication.
-UsernamePassword
+Abstract
 Authenti
@@ -1070,30 +1070,32 @@
 ty.core.
-Authentication
+GrantedAuthority
 ;%0Aimport
@@ -1121,32 +1121,48 @@
 k.security.core.
+authority.Simple
 GrantedAuthority
@@ -1208,40 +1208,103 @@
 ore.
-authority.SimpleGrantedAuthority
+context.SecurityContextHolder;%0Aimport org.springframework.security.core.userdetails.UserDetails
 ;%0Aim
@@ -3119,16 +3119,18 @@
 ER%22));%0A%0A
+//
 %09%09Authen
@@ -3229,16 +3229,18 @@
  list);%0A
+//
 %09%09%0A%09%09tok
@@ -3333,16 +3333,314 @@
 e));%0A%09%09%0A
+%09%09UserDetails user = new org.springframework.security.core.userdetails.User(nativeUser.getId().toString(), %22%22, list);%0A%09%09AbstractAuthenticationToken a = new AACAuthenticationToken(user, null, authority, list);%0A%09%09a.setDetails(authority);%0A%09%09SecurityContextHolder.getContext().setAuthentication(a);%0A%09%09%0A
 %09%09OAuth2
@@ -3738,20 +3738,17 @@
 lient), 
-user
+a
 );%0A%09%09ret

Fix for token granter