<commit_before>// Copyright (c) 2014-2016 Bitmark Inc.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.

package api

import (
	"encoding/json"
	"github.com/bitmark-inc/bitmark-mgmt/fault"
	"github.com/bitmark-inc/logger"
	"golang.org/x/crypto/bcrypt"
	"net/http"
	"time"
)

const (
	cookieName = "bitmark-mgmt"
)

type Response struct {
	Ok     bool        `json:"ok"`
	Result interface{} `json:"result"`
}

func writeApiResponse(w http.ResponseWriter, response *Response) error {
	// w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Content-Type", "text/json; charset=utf-8")
	if b, err := json.MarshalIndent(response, "", "  "); nil != err {
		return fault.ErrJsonParseFail
	} else {
		w.Write(b)
	}

	return nil
}

func writeApiResponseAndSetCookie(w http.ResponseWriter, response *Response) error {
	// set cookie
	if err := setCookie(w); nil != err {
		w.WriteHeader(http.StatusUnauthorized)
		return err
	}

	return writeApiResponse(w, response)
}

func setCookie(w http.ResponseWriter) error {

	cookie := &http.Cookie{
		Name:   cookieName,
		Secure: true,
	}

	timeStr := time.Now().String()
	cookiePlain = cookieName + ":" + timeStr
	cookieCipher, err := bcrypt.GenerateFromPassword([]byte(cookiePlain), bcrypt.DefaultCost)
	if nil != err {
		//fmt.Printf("Error: %v\n", err)
		cookie.MaxAge = -1
		http.SetCookie(w, cookie)
		return fault.ApiErrSetAuthorize
	}

	cookie.Value = string(cookieCipher)
	cookie.MaxAge = 10 * 60 //seconds
	http.SetCookie(w, cookie)
	return nil
}

func WriteGlobalErrorResponse(w http.ResponseWriter, err error, log *logger.L) error {
	response := &Response{
		Ok:     false,
		Result: err,
	}
	if err := writeApiResponseAndSetCookie(w, response); nil != err {
		log.Errorf("writeApiResponseAndSetCookie error: %v", err)
		return err
	}

	return nil
}

var cookiePlain string

func GetAndCheckCookie(w http.ResponseWriter, req *http.Request, log *logger.L) error {
	reqCookie, err := req.Cookie(cookieName)
	if nil != err {
		log.Errorf("request cookie error: %v", err)
		return fault.ApiErrUnauthorized
	}

	if err := bcrypt.CompareHashAndPassword([]byte(reqCookie.Value), []byte(cookiePlain)); nil != err {
		log.Errorf("decrypt cookie error: %v", err)
		return fault.ApiErrChekAuthorize
	}

	return nil
}

func SetCORSHeader(w http.ResponseWriter, req *http.Request) {
	if origin := req.Header.Get("Origin"); origin != "" {
		w.Header().Set("Access-Control-Allow-Origin", origin)
	}
	w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token")
	w.Header().Set("Access-Control-Allow-Credentials", "true")
}<commit_msg>modify cookie function<commit_after>// Copyright (c) 2014-2016 Bitmark Inc.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.

package api

import (
	"encoding/json"
	"github.com/bitmark-inc/bitmark-mgmt/fault"
	"github.com/bitmark-inc/logger"
	"golang.org/x/crypto/bcrypt"
	"net/http"
	"sync"
	"time"
)

const (
	cookieName = "bitmark-mgmt"
)

type Response struct {
	Ok     bool        `json:"ok"`
	Result interface{} `json:"result"`
}

func writeApiResponse(w http.ResponseWriter, response *Response) error {
	// w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Content-Type", "text/json; charset=utf-8")
	if b, err := json.MarshalIndent(response, "", "  "); nil != err {
		return fault.ErrJsonParseFail
	} else {
		w.Write(b)
	}

	return nil
}

func writeApiResponseAndSetCookie(w http.ResponseWriter, response *Response) error {
	// set cookie
	if err := setCookie(w); nil != err {
		w.WriteHeader(http.StatusUnauthorized)
		return err
	}

	return writeApiResponse(w, response)
}


type cookie struct {
	sync.RWMutex
	expireTime time.Time
	cipher string
}

var globalCookie [2]cookie // 0 is recent cookie, 1 is previous
var cookieExpireDuration = 10

func setCookie(w http.ResponseWriter) error {
	cookie := &http.Cookie{
		Name:   cookieName,
		Secure: true,
	}

	globalCookie[0].Lock()
	defer globalCookie[0].Unlock()
	globalCookie[1].Lock()
	defer globalCookie[1].Unlock()

	// check if globalCookie need to be updated
	localTime := time.Now().Add(time.Duration(2)*time.Minute)
	if localTime.After(globalCookie[0].expireTime) {
	// cookie will be expired in 2 minutes
		globalCookie[1].expireTime = globalCookie[0].expireTime
		globalCookie[0].expireTime = time.Now().Add(time.Duration(cookieExpireDuration)*time.Minute)

		cookieCipher, err := bcrypt.GenerateFromPassword([]byte(globalCookie[0].expireTime.String()), bcrypt.DefaultCost)
		if nil != err {
			cookie.MaxAge = -1
			http.SetCookie(w, cookie)
			return fault.ApiErrSetAuthorize
		}
		globalCookie[0].cipher = string(cookieCipher)

	}

	cookie.Value = globalCookie[0].cipher
	cookie.MaxAge = cookieExpireDuration * 60 //seconds
	http.SetCookie(w, cookie)
	return nil


}

func WriteGlobalErrorResponse(w http.ResponseWriter, err error, log *logger.L) error {
	response := &Response{
		Ok:     false,
		Result: err,
	}
	if err := writeApiResponseAndSetCookie(w, response); nil != err {
		log.Errorf("writeApiResponseAndSetCookie error: %v", err)
		return err
	}

	return nil
}


func GetAndCheckCookie(w http.ResponseWriter, req *http.Request, log *logger.L) error {
	reqCookie, err := req.Cookie(cookieName)
	if nil != err {
		log.Errorf("request cookie error: %v", err)
		return fault.ApiErrUnauthorized
	}

	globalCookie[0].Lock()
	defer globalCookie[0].Unlock()
	globalCookie[1].Lock()
	defer globalCookie[1].Unlock()

	for _, c := range globalCookie {
		if err := bcrypt.CompareHashAndPassword([]byte(reqCookie.Value), []byte(c.expireTime.String())); nil == err {
			return nil
		}
	}

	log.Errorf("decrypt cookie error: %v", err)
	return fault.ApiErrChekAuthorize
}

func SetCORSHeader(w http.ResponseWriter, req *http.Request) {
	if origin := req.Header.Get("Origin"); origin != "" {
		w.Header().Set("Access-Control-Allow-Origin", origin)
	}
	w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token")
	w.Header().Set("Access-Control-Allow-Credentials", "true")
}
{'fraction_non_alphanumeric': 0.14617834394904458, 'fraction_numerical': 0.007643312101910828, 'mean_word_length': 4.400687876182287, 'pattern_counts': {'":': 1, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6362729', 'n_tokens_mistral': 2235, 'n_tokens_neox': 2125, 'n_words': 487}