rano/pkg/user/token.go

55 lines
1.1 KiB
Go
Raw Normal View History

2024-11-18 15:23:13 +00:00
// Copyright 2024 Patial Tech. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
2024-11-17 16:58:29 +00:00
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()
2024-11-19 05:10:30 +00:00
return uid.Encode(
2024-11-17 16:58:29 +00:00
uint64(userID),
1, // identifies that its token to verify email
uint64(expiresAt),
2024-11-19 05:10:30 +00:00
)
2024-11-17 16:58:29 +00:00
}
// 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
}