/*
 * Copyright 2015 the original author or authors.
 *
 * 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 leap.web.security.user;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import leap.core.BeanFactory;
import leap.core.annotation.Inject;
import leap.core.ioc.PostCreateBean;
import leap.core.security.Authentication;
import leap.core.security.Credentials;
import leap.core.security.UserPrincipal;
import leap.core.security.token.TokenCredentials;
import leap.core.security.token.jwt.JWT;
import leap.core.security.token.jwt.JwtSigner;
import leap.core.security.token.jwt.JwtVerifier;
import leap.core.security.token.jwt.MacSigner;
import leap.lang.Out;
import leap.lang.Strings;
import leap.web.Request;
import leap.web.Response;
import leap.web.security.SecurityConfig;
import leap.web.security.authc.AuthenticationException;
import leap.web.security.authc.TokenAuthenticator;
import leap.web.security.authc.credentials.CredentialsAuthenticationContext;

public class JwtTokenAuthenticator extends UsernameBasedTokenAuthenticator implements TokenAuthenticator, PostCreateBean {
	
	public static final String CLAIM_NAME = "name"; //username
	
    @Inject
    protected SecurityConfig   config;
    protected JwtSigner        signer;
    protected JwtVerifier      verifier;
	
	@Override
	public String generateAuthenticationToken(Request request, Response response, Authentication authc) {
		return signer.sign(createClaims(authc));
	}

	@Override
    public boolean authenticate(CredentialsAuthenticationContext context, Credentials credentials, Out<UserPrincipal> user) throws AuthenticationException {
		if(credentials instanceof TokenCredentials) {
			String token = ((TokenCredentials) credentials).getToken();
			
			Map<String, Object> claims = verifier.verify(token);
			
			String username = (String)claims.get(CLAIM_NAME);
			String jti = (String)claims.get(JWT.CLAIM_JWT_ID);
			
			if(Strings.isEmpty(username)||Strings.isEmpty(jti)) {
				return false;
			}
			
			UserDetails details = resolveUserDetails(context, username, claims);
			if(null == details) {
				return false;
			}

			user.set(details);
			return true;
		}
		
		return false;
    }

	@Override
	protected Map<String, Object> createDefaultClaims(Authentication auth) {
		UserPrincipal user = auth.getUser();
		
		Map<String, Object> claims = new HashMap<>();

		claims.put(JWT.CLAIM_JWT_ID, UUID.randomUUID().toString());
		claims.put(CLAIM_NAME, user.getLoginName());
		
		return claims;
	}
	
	@Override
    public void postCreate(BeanFactory factory) throws Throwable {
	    if(null == signer) {
	        signer   = new MacSigner(config.getSecret(), config.getDefaultAuthenticationExpires());
	        verifier = (JwtVerifier)signer;
	    }
    }

	public JwtSigner getSigner() {
		return signer;
	}

	public void setSigner(JwtSigner tokenSigner) {
		this.signer = tokenSigner;
	}

	public JwtVerifier getVerifier() {
		return verifier;
	}

	public void setVerifier(JwtVerifier tokenVerifier) {
		this.verifier = tokenVerifier;
	}
	
}
@@ -2581,21 +2581,55 @@
 %0D%0A%09%09%09%7D%0D%0A
+%0D%0A
 %09%09%09
+if(sc.getUserStore() != null) %7B
 %0D%0A
+%09
 %09%09%09UserD
@@ -2696,18 +2696,20 @@
 s);%0D%0A%09%09%09
+%09
 if
+ 
 (null ==
@@ -2717,32 +2717,33 @@
 details) %7B%0D%0A%09%09%09%09
+%09
 return false;%0D%0A%09
@@ -2744,21 +2744,28 @@
 se;%0D%0A%09%09%09
-%7D%0D%0A%0D%0A
+%09%7Delse %7B%0D%0A%09%09
 %09%09%09user.
@@ -2782,16 +2782,18 @@
 s);%0D%0A%09%09%09
+%09%09
 return t
@@ -2798,16 +2798,316 @@
  true;%0D%0A
+%09%09%09%09%7D%0D%0A%09%09%09%7Delse %7B%0D%0A                SimpleUserDetails details = new SimpleUserDetails();%0D%0A                details.setId(jti);%0D%0A                details.setLoginName(username);%0D%0A                details.setName(username);%0D%0A                user.set(details);%0D%0A                return true;%0D%0A            %7D%0D%0A
 %09%09%7D%0D%0A%09%09%0D

fix jwt token authentication without UserStore