package com.coding4people.mosquitoreport.api.factories;

import java.util.Base64;

import javax.inject.Inject;
import javax.ws.rs.ForbiddenException;
import javax.ws.rs.container.ContainerRequestContext;

import org.glassfish.hk2.api.Factory;
import org.glassfish.jersey.process.internal.RequestScoped;

import com.coding4people.mosquitoreport.api.models.User;
import com.coding4people.mosquitoreport.api.repositories.UserRepository;

@RequestScoped
public class CurrentUserFactory implements Factory<User> {
    User user;

    @Inject
    public CurrentUserFactory(UserRepository userRepository, ContainerRequestContext requestContext) {
        String authorization = requestContext.getHeaderString("Authorization");

        if (authorization == null || authorization.isEmpty() || !authorization.startsWith("Token ")) {
            throw new ForbiddenException("Missing 'Authorization' HTTP header");
        }

        // TODO implement decent authorization algorithm
        final String guid = new String(Base64.getDecoder().decode(authorization.substring(6)));

        user = userRepository.load(guid);

        if (user == null) {
            throw new ForbiddenException("User not authenticate");
        }
    }

    @Override
    public void dispose(User user) {
    }

    @Override
    public User provide() {
        return user;
    }
}

@@ -978,20 +978,46 @@
     
-final 
 String
+ guid;%0A        try %7B%0A           
  gui
@@ -1087,16 +1087,131 @@
 ng(6)));
+%0A        %7D catch (Throwable t) %7B%0A            throw new ForbiddenException(%22Invalid authorization token%22);%0A        %7D
 %0A%0A      

Handle non base64 tokens