51 lines
1.2 KiB
Go
51 lines
1.2 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
g "platform/web/globals"
|
|
"platform/web/globals/orm"
|
|
m "platform/web/models"
|
|
q "platform/web/queries"
|
|
"time"
|
|
|
|
"gorm.io/gen/field"
|
|
)
|
|
|
|
func FindSession(accessToken string, now time.Time) (*m.Session, error) {
|
|
return q.Session.
|
|
Preload(field.Associations).
|
|
Where(
|
|
q.Session.AccessToken.Eq(accessToken),
|
|
q.Session.AccessTokenExpires.Gt(orm.LocalDateTime(now)),
|
|
).First()
|
|
}
|
|
|
|
func FindSessionByRefresh(refreshToken string, now time.Time) (*m.Session, error) {
|
|
return q.Session.
|
|
Preload(field.Associations).
|
|
Where(
|
|
q.Session.RefreshToken.Eq(refreshToken),
|
|
q.Session.RefreshTokenExpires.Gt(orm.LocalDateTime(now)),
|
|
).First()
|
|
}
|
|
|
|
func SaveSession(session *m.Session) error {
|
|
return q.Session.Save(session)
|
|
}
|
|
|
|
func RemoveSession(ctx context.Context, accessToken string, refreshToken string) error {
|
|
g.Redis.Del(ctx, accessKey(accessToken), refreshKey(refreshToken))
|
|
return nil
|
|
}
|
|
|
|
// 令牌键的格式为 "session:<token>"
|
|
func accessKey(token string) string {
|
|
return fmt.Sprintf("session:%s", token)
|
|
}
|
|
|
|
// 刷新令牌键的格式为 "session:refreshKey:<token>"
|
|
func refreshKey(token string) string {
|
|
return fmt.Sprintf("session:refresh:%s", token)
|
|
}
|