1package oauth
2
3import (
4 "errors"
5 "fmt"
6 "net/url"
7 "time"
8
9 "github.com/haileyok/cocoon/internal/helpers"
10 "github.com/haileyok/cocoon/oauth/constants"
11 "github.com/haileyok/cocoon/oauth/provider"
12)
13
14func GenerateCode() string {
15 h, _ := helpers.RandomHex(constants.CodeBytesLength)
16 return constants.CodePrefix + h
17}
18
19func GenerateTokenId() string {
20 h, _ := helpers.RandomHex(constants.TokenIdBytesLength)
21 return constants.TokenIdPrefix + h
22}
23
24func GenerateRefreshToken() string {
25 h, _ := helpers.RandomHex(constants.RefreshTokenBytesLength)
26 return constants.RefreshTokenPrefix + h
27}
28
29func GenerateRequestId() string {
30 h, _ := helpers.RandomHex(constants.RequestIdBytesLength)
31 return constants.RequestIdPrefix + h
32}
33
34func EncodeRequestUri(reqId string) string {
35 return constants.RequestUriPrefix + url.QueryEscape(reqId)
36}
37
38func DecodeRequestUri(reqUri string) (string, error) {
39 if len(reqUri) < len(constants.RequestUriPrefix) {
40 return "", errors.New("invalid request uri")
41 }
42
43 reqIdEnc := reqUri[len(constants.RequestUriPrefix):]
44 reqId, err := url.QueryUnescape(reqIdEnc)
45 if err != nil {
46 return "", fmt.Errorf("could not unescape request id: %w", err)
47 }
48
49 return reqId, nil
50}
51
52type SessionAgeResult struct {
53 SessionAge time.Duration
54 RefreshAge time.Duration
55 SessionExpired bool
56 RefreshExpired bool
57}
58
59func GetSessionAgeFromToken(t provider.OauthToken) SessionAgeResult {
60 sessionLifetime := constants.PublicClientSessionLifetime
61 refreshLifetime := constants.PublicClientRefreshLifetime
62 if t.ClientAuth.Method != "none" {
63 sessionLifetime = constants.ConfidentialClientSessionLifetime
64 refreshLifetime = constants.ConfidentialClientRefreshLifetime
65 }
66
67 res := SessionAgeResult{}
68
69 res.SessionAge = time.Since(t.CreatedAt)
70 if res.SessionAge > sessionLifetime {
71 res.SessionExpired = true
72 }
73
74 refreshAge := time.Since(t.UpdatedAt)
75 if refreshAge > refreshLifetime {
76 res.RefreshExpired = true
77 }
78
79 return res
80}