2022-01-04 20:23:25 +00:00
|
|
|
package cookie
|
|
|
|
|
|
|
|
import (
|
2022-05-16 06:15:09 +00:00
|
|
|
"crypto/rand"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
2022-01-04 20:23:25 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var availableChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@!.#$_"
|
|
|
|
|
|
|
|
func GenToken(length int) string {
|
2022-05-16 06:15:09 +00:00
|
|
|
ll := len(availableChars)
|
|
|
|
b := make([]byte, length)
|
|
|
|
rand.Read(b)
|
|
|
|
for i := 0; i < length; i++ {
|
|
|
|
b[i] = availableChars[int(b[i])%ll]
|
|
|
|
}
|
|
|
|
return string(b)
|
2022-01-04 20:23:25 +00:00
|
|
|
}
|
|
|
|
|
2022-08-03 02:46:34 +00:00
|
|
|
func StoreToken(field string, token string, w http.ResponseWriter, ttl int) {
|
2022-05-16 06:15:09 +00:00
|
|
|
cookie := http.Cookie{
|
|
|
|
Name: field,
|
|
|
|
Value: token,
|
2022-08-03 02:46:34 +00:00
|
|
|
Expires: time.Now().Add(time.Duration(ttl) * time.Minute),
|
2022-05-16 06:15:09 +00:00
|
|
|
}
|
2022-01-04 20:23:25 +00:00
|
|
|
|
2022-05-16 06:15:09 +00:00
|
|
|
http.SetCookie(w, &cookie)
|
2022-01-04 20:23:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func GetToken(field string, req *http.Request) (string, error) {
|
2022-05-16 06:15:09 +00:00
|
|
|
c, err := req.Cookie(field)
|
|
|
|
if err == nil {
|
|
|
|
return c.Value, nil
|
|
|
|
} else {
|
|
|
|
return "", err
|
|
|
|
}
|
2022-01-04 20:23:25 +00:00
|
|
|
}
|