puerta/internal/auth/duration.go

58 lines
1.1 KiB
Go
Raw Normal View History

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"
)
var DefaultTTL = TTL("30d")
2022-12-30 06:51:51 +00:00
type TTL string
2022-12-30 06:51:51 +00:00
func (ttl TTL) ToDuration() (res time.Duration, err error) {
suffix := ttl[len(ttl)-1]
2022-12-30 06:51:51 +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:
err = fmt.Errorf("unknown suffix for time duration %s", string(suffix))
return
2022-12-30 06:51:51 +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 {
return
2022-12-30 06:51:51 +00:00
}
toParse = fmt.Sprintf("%dh", days*multiplier)
2022-12-30 06:51:51 +00:00
}
res, err = time.ParseDuration(toParse)
return
2022-12-30 06:51:51 +00:00
}
func (ttl *TTL) FromNow() time.Time {
d, _ := ttl.ToDuration()
return time.Now().Add(d)
2022-12-30 06:51:51 +00:00
}
func (ttl *TTL) Seconds() int {
d, _ := ttl.ToDuration()
return int(d.Seconds())
2022-12-30 06:51:51 +00:00
}
// var _ = (db.Unmarshaler(&TTL{}))
// var _ = (db.Marshaler(&TTL{}))