2022-12-30 06:51:51 +00:00
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
// Copyright © 2022 Roberto Hidalgo <nidito@un.rob.mx>
|
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"strconv"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2023-01-02 06:54:23 +00:00
|
|
|
var DefaultTTL = TTL("30d")
|
2022-12-30 06:51:51 +00:00
|
|
|
|
2023-01-02 06:54:23 +00:00
|
|
|
type TTL string
|
2022-12-30 06:51:51 +00:00
|
|
|
|
2023-01-02 06:54:23 +00:00
|
|
|
func (ttl TTL) ToDuration() (res time.Duration, err error) {
|
2023-01-03 07:40:38 +00:00
|
|
|
if ttl == "" {
|
|
|
|
return
|
|
|
|
}
|
2023-01-02 06:54:23 +00:00
|
|
|
suffix := ttl[len(ttl)-1]
|
2022-12-30 06:51:51 +00:00
|
|
|
|
2023-01-02 06:54:23 +00:00
|
|
|
toParse := string(ttl)
|
2022-12-30 06:51:51 +00:00
|
|
|
if suffix == 'd' || suffix == 'w' || suffix == 'M' {
|
|
|
|
multiplier := 1
|
|
|
|
switch suffix {
|
|
|
|
case 'd':
|
|
|
|
multiplier = 24
|
|
|
|
case 'w':
|
|
|
|
multiplier = 24 * 7
|
|
|
|
case 'M':
|
|
|
|
multiplier = 24 * 7 * 30
|
|
|
|
default:
|
2023-01-02 06:54:23 +00:00
|
|
|
err = fmt.Errorf("unknown suffix for time duration %s", string(suffix))
|
|
|
|
return
|
2022-12-30 06:51:51 +00:00
|
|
|
}
|
|
|
|
|
2023-01-02 06:54:23 +00:00
|
|
|
toParse = toParse[0 : len(toParse)-1]
|
|
|
|
var days int
|
|
|
|
days, err = strconv.Atoi(toParse)
|
2022-12-30 06:51:51 +00:00
|
|
|
if err != nil {
|
2023-01-02 06:54:23 +00:00
|
|
|
return
|
2022-12-30 06:51:51 +00:00
|
|
|
}
|
|
|
|
|
2023-01-02 06:54:23 +00:00
|
|
|
toParse = fmt.Sprintf("%dh", days*multiplier)
|
2022-12-30 06:51:51 +00:00
|
|
|
}
|
2023-01-02 06:54:23 +00:00
|
|
|
res, err = time.ParseDuration(toParse)
|
|
|
|
return
|
2022-12-30 06:51:51 +00:00
|
|
|
}
|
|
|
|
|
2023-01-02 06:54:23 +00:00
|
|
|
func (ttl *TTL) FromNow() time.Time {
|
|
|
|
d, _ := ttl.ToDuration()
|
|
|
|
return time.Now().Add(d)
|
2022-12-30 06:51:51 +00:00
|
|
|
}
|
|
|
|
|
2023-01-02 06:54:23 +00:00
|
|
|
func (ttl *TTL) Seconds() int {
|
|
|
|
d, _ := ttl.ToDuration()
|
|
|
|
return int(d.Seconds())
|
2022-12-30 06:51:51 +00:00
|
|
|
}
|