51 lines
1.0 KiB
Go
51 lines
1.0 KiB
Go
|
package user
|
||
|
|
||
|
import (
|
||
|
"errors"
|
||
|
"time"
|
||
|
|
||
|
"gitserver.in/patialtech/rano/util/uid"
|
||
|
)
|
||
|
|
||
|
var (
|
||
|
ErrExpiredToken = errors.New("expired token")
|
||
|
ErrInvalidToken = errors.New("invalid token")
|
||
|
)
|
||
|
|
||
|
// newTokenToVerifyEmail for a user for given duration
|
||
|
func newTokenToVerifyEmail(userID int64, d time.Duration) (string, error) {
|
||
|
expiresAt := time.Now().Add(d).UTC().UnixMilli()
|
||
|
return uid.Encode([]uint64{
|
||
|
uint64(userID),
|
||
|
1, // identifies that its token to verify email
|
||
|
uint64(expiresAt),
|
||
|
})
|
||
|
}
|
||
|
|
||
|
// tokenToVerifyEmail will check for valid email token that is yet not expired
|
||
|
//
|
||
|
// returns userID on success
|
||
|
func tokenToVerifyEmail(token string) (int64, error) {
|
||
|
ids, err := uid.Decode(token)
|
||
|
if err != nil {
|
||
|
return 0, nil
|
||
|
}
|
||
|
|
||
|
// slice must have 3 entries
|
||
|
if len(ids) != 3 {
|
||
|
return 0, ErrInvalidToken
|
||
|
}
|
||
|
|
||
|
// must be an email verify token
|
||
|
if ids[1] != 1 {
|
||
|
return 0, ErrInvalidToken
|
||
|
}
|
||
|
|
||
|
// check expiry
|
||
|
if int64(ids[2]) < time.Now().UTC().UnixMilli() {
|
||
|
return 0, ErrExpiredToken
|
||
|
}
|
||
|
|
||
|
return int64(ids[0]), nil
|
||
|
}
|