2015-08-18 05:57:27 +05:30
|
|
|
package refresh
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rand"
|
|
|
|
"errors"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
DefaultRefreshTokenPayloadLength = 64
|
|
|
|
TokenDelimer = "/"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
ErrorInvalidUserID = errors.New("invalid user ID")
|
|
|
|
ErrorInvalidClientID = errors.New("invalid client ID")
|
2015-09-01 07:54:45 +05:30
|
|
|
|
|
|
|
ErrorInvalidToken = errors.New("invalid token")
|
2015-08-18 05:57:27 +05:30
|
|
|
)
|
|
|
|
|
2015-09-01 07:54:45 +05:30
|
|
|
type RefreshTokenGenerator func() ([]byte, error)
|
2015-08-18 05:57:27 +05:30
|
|
|
|
2015-09-01 07:54:45 +05:30
|
|
|
func (g RefreshTokenGenerator) Generate() ([]byte, error) {
|
2015-08-18 05:57:27 +05:30
|
|
|
return g()
|
|
|
|
}
|
|
|
|
|
2015-09-01 07:54:45 +05:30
|
|
|
func DefaultRefreshTokenGenerator() ([]byte, error) {
|
2015-08-18 05:57:27 +05:30
|
|
|
// TODO(yifan) Remove this duplicated token generate function.
|
|
|
|
b := make([]byte, DefaultRefreshTokenPayloadLength)
|
|
|
|
n, err := rand.Read(b)
|
|
|
|
if err != nil {
|
2015-09-01 07:54:45 +05:30
|
|
|
return nil, err
|
2015-09-05 01:15:32 +05:30
|
|
|
}
|
|
|
|
if n != DefaultRefreshTokenPayloadLength {
|
2015-09-01 07:54:45 +05:30
|
|
|
return nil, errors.New("unable to read enough random bytes")
|
2015-08-18 05:57:27 +05:30
|
|
|
}
|
2015-09-01 07:54:45 +05:30
|
|
|
return b, nil
|
2015-08-18 05:57:27 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
type RefreshTokenRepo interface {
|
|
|
|
// Create generates and returns a new refresh token for the given client-user pair.
|
|
|
|
// On success the token will be return.
|
|
|
|
Create(userID, clientID string) (string, error)
|
|
|
|
|
|
|
|
// Verify verifies that a token belongs to the client, and returns the corresponding user ID.
|
|
|
|
// Note that this assumes the client validation is currently done in the application layer,
|
|
|
|
Verify(clientID, token string) (string, error)
|
|
|
|
|
|
|
|
// Revoke deletes the refresh token if the token belongs to the given userID.
|
|
|
|
Revoke(userID, token string) error
|
|
|
|
}
|