57 lines
1.5 KiB
Go
57 lines
1.5 KiB
Go
package auth
|
|
|
|
import (
|
|
"crypto/hmac"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"errors"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
func VerifyPassword(hash, password string) bool {
|
|
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
|
|
}
|
|
|
|
var dummyPasswordHash = func() string {
|
|
hash, _ := bcrypt.GenerateFromPassword([]byte("sea-vhost-dummy-credential"), bcrypt.DefaultCost)
|
|
return string(hash)
|
|
}()
|
|
|
|
func VerifyPasswordConstantWork(hash, password string) bool {
|
|
if hash == "" {
|
|
_ = bcrypt.CompareHashAndPassword([]byte(dummyPasswordHash), []byte(password))
|
|
return false
|
|
}
|
|
return VerifyPassword(hash, password)
|
|
}
|
|
|
|
func HashPassword(password string) (string, error) {
|
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
|
return string(hash), err
|
|
}
|
|
|
|
func NewSessionToken(secret string) (string, error) {
|
|
random := make([]byte, 32)
|
|
if _, err := rand.Read(random); err != nil {
|
|
return "", err
|
|
}
|
|
mac := hmac.New(sha256.New, []byte(secret))
|
|
_, _ = mac.Write(random)
|
|
payload := append(random, mac.Sum(nil)...)
|
|
return base64.RawURLEncoding.EncodeToString(payload), nil
|
|
}
|
|
|
|
func ValidateSessionToken(secret, token string) bool {
|
|
payload, err := base64.RawURLEncoding.DecodeString(token)
|
|
if err != nil || len(payload) != 64 {
|
|
return false
|
|
}
|
|
mac := hmac.New(sha256.New, []byte(secret))
|
|
_, _ = mac.Write(payload[:32])
|
|
return hmac.Equal(payload[32:], mac.Sum(nil))
|
|
}
|
|
|
|
var ErrInvalidCredentials = errors.New("invalid credentials")
|