Last active
August 29, 2015 14:05
-
-
Save nl5887/f654d670e1c28b809740 to your computer and use it in GitHub Desktop.
Function to validate Pyramid authentication tickets (auth_tkt cookie)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"crypto/sha512" | |
"encoding/hex" | |
"fmt" | |
"net/http" | |
"strconv" | |
"strings" | |
) | |
func authorize(r *http.Request) (userid string, err error) { | |
cookie, err := r.Cookie("auth_tkt") | |
if err != nil { | |
err = fmt.Errorf("No auth ticket") | |
return "", err | |
} | |
tkt := cookie.Value | |
hash := sha512.New() | |
digest_size := hash.Size() * 2 | |
digest := tkt[:digest_size] | |
// in GO > 1, Btoi64 | |
timestamp, err := strconv.ParseInt(tkt[digest_size:digest_size+8], 16, 64) // should convert hex (08) to int | |
// TODO: Validate the timestamp | |
ip := "0.0.0.0" | |
strings.Split(ip, ".") | |
bt4 := []byte{ | |
byte(0), | |
byte(0), | |
byte(0), | |
byte(0), | |
byte((timestamp & 0xff000000) >> 24), | |
byte((timestamp & 0x00ff0000) >> 16), | |
byte((timestamp & 0x0000ff00) >> 8), | |
byte((timestamp & 0x000000ff)), | |
} | |
// TODO: Validate IP address | |
secret := "SECRET KEY" | |
tokens := "" | |
userid = strings.Split(tkt[digest_size+8:], "!")[0] | |
userdata := strings.Split(tkt[digest_size+8:], "!")[1] | |
hash.Write([]byte(fmt.Sprintf("%s%s%v\x00%s\x00%s", bt4, secret, userid, tokens, userdata))) | |
signature1 := hex.EncodeToString(hash.Sum(nil)) | |
hash = sha512.New() | |
hash.Write([]byte(fmt.Sprintf("%s%s", signature1, secret))) | |
signature := hex.EncodeToString(hash.Sum(nil)) | |
// should compare bytes instead of strings | |
if signature != digest { | |
// return authorization failed http error | |
err = fmt.Errorf("Invalid signature") | |
return "", err | |
} | |
return userid, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment