git.iko.soy/typeable/oauth2-proxy
on v1.1 help sign in
61 lines 1.5 kB history raw
1package main
3import (
4 "crypto/hmac"
5 "crypto/sha1"
6 "encoding/base64"
7 "fmt"
8 "net/http"
9 "strconv"
10 "strings"
11 "time"
14func validateCookie(cookie *http.Cookie, seed string) (string, bool) {
15 // value, timestamp, sig
16 parts := strings.Split(cookie.Value, "|")
17 if len(parts) != 3 {
18 return "", false
19 }
20 sig := cookieSignature(seed, cookie.Name, parts[0], parts[1])
21 if checkHmac(parts[2], sig) {
22 ts, err := strconv.Atoi(parts[1])
23 if err == nil && int64(ts) > time.Now().Add(time.Duration(24)*7*time.Hour*-1).Unix() {
24 // it's a valid cookie. now get the contents
25 rawValue, err := base64.URLEncoding.DecodeString(parts[0])
26 if err == nil {
27 return string(rawValue), true
28 }
29 }
30 }
31 return "", false
34func signedCookieValue(seed string, key string, value string) string {
35 encodedValue := base64.URLEncoding.EncodeToString([]byte(value))
36 timeStr := fmt.Sprintf("%d", time.Now().Unix())
37 sig := cookieSignature(seed, key, encodedValue, timeStr)
38 cookieVal := fmt.Sprintf("%s|%s|%s", encodedValue, timeStr, sig)
39 return cookieVal
42func cookieSignature(args ...string) string {
43 h := hmac.New(sha1.New, []byte(args[0]))
44 for _, arg := range args[1:] {
45 h.Write([]byte(arg))
46 }
47 var b []byte
48 b = h.Sum(b)
49 return base64.URLEncoding.EncodeToString(b)
52func checkHmac(input, expected string) bool {
53 inputMAC, err1 := base64.URLEncoding.DecodeString(input)
54 if err1 == nil {
55 expectedMAC, err2 := base64.URLEncoding.DecodeString(expected)
56 if err2 == nil {
57 return hmac.Equal(inputMAC, expectedMAC)
58 }
59 }
60 return false