package com.thoughtworks.securityinourdna;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.SQLException;

@RestController
public class VendorPortalController {

    private final UserRepo userRepo;

    @Autowired
    public VendorPortalController(UserRepo userRepo) {
        this.userRepo = userRepo;
    }

    @RequestMapping(value = "/vendor/delete/{name}", method = RequestMethod.POST)
    public String deleteVendor(@PathVariable String name,
                               @RequestParam String csrfToken,
                               HttpServletRequest request,
                               HttpSession session) throws SQLException {
        if (loggedIn(session) && csrfTokenCorrect(csrfToken, request)) {
            userRepo.delete(name);
            return name;
        }

        throw new UnauthorizedResponse();
    }

    private boolean loggedIn(HttpSession session) {
        final UserState userState = (UserState) session.getAttribute("userState");
        return userState != null && userState.isLoggedIn();
    }

    private boolean csrfTokenCorrect(String csrfToken, HttpServletRequest request) {
        String csrfTokenFromCookie = null;
        for (Cookie cookie : request.getCookies()) {
            if (cookie.getName().equals("csrfToken")) {
                csrfTokenFromCookie = cookie.getValue();
            }
        }

        if (csrfTokenFromCookie == null) {
            return false;
        } else {
            return csrfTokenFromCookie.equals(csrfToken);
        }
    }

}

@@ -909,16 +909,29 @@
  request
+.getCookies()
 )) %7B%0A   
@@ -1308,34 +1308,24 @@
 en, 
-HttpServletRequest requ
+Cookie%5B%5D cooki
 es
-t
 ) %7B%0A
@@ -1396,36 +1396,23 @@
 ookie : 
-request.getC
+c
 ookies
-()
 ) %7B%0A    
@@ -1655,55 +1655,559 @@
 rn c
-srfTokenFromCookie.equals(csrfToken);%0A        %7D
+onstantTimeEquals(csrfTokenFromCookie, csrfToken);%0A        %7D%0A    %7D%0A%0A    /*%0A     * http://codahale.com/a-lesson-in-timing-attacks/%0A     */%0A    private boolean constantTimeEquals(String a, String b) %7B%0A        byte%5B%5D byteArrayA = a.getBytes();%0A        byte%5B%5D byteArrayB = b.getBytes();%0A        %0A        if (byteArrayA.length != byteArrayB.length) %7B%0A            return false;%0A        %7D%0A%0A        int result = 0;%0A        for (int i = 0; i %3C byteArrayA.length; i++) %7B%0A            result %7C= byteArrayA%5Bi%5D %5E byteArrayB%5Bi%5D;%0A        %7D%0A        return result == 0;
 %0A   

switch to constant time string comparison