photoprism/internal/entity/auth_client_access_token.go
Michael Mayer 7d78ee803a Use human-friendly secrets & names for personal access tokens #808 #3943
Signed-off-by: Michael Mayer <michael@photoprism.app>
2024-01-10 17:23:08 +01:00

41 lines
1.1 KiB
Go

package entity
import (
"github.com/photoprism/photoprism/pkg/authn"
"github.com/photoprism/photoprism/pkg/clean"
"github.com/photoprism/photoprism/pkg/rnd"
)
// NewClientAccessToken returns a new access token session instance
// that can be used to access the API with unregistered clients.
func NewClientAccessToken(name string, lifetime int64, scope string, user *User) *Session {
sess := NewSession(lifetime, 0)
if name == "" {
name = rnd.Name()
}
sess.AuthID = clean.Name(name)
sess.AuthProvider = authn.ProviderClient.String()
sess.AuthMethod = authn.MethodAccessToken.String()
sess.AuthScope = clean.Scope(scope)
if user != nil {
sess.SetUser(user)
sess.SetAuthToken(rnd.AuthSecret())
}
return sess
}
// CreateClientAccessToken initializes and creates a new access token session
// that can be used to access the API with unregistered clients.
func CreateClientAccessToken(name string, lifetime int64, scope string, user *User) (*Session, error) {
sess := NewClientAccessToken(name, lifetime, scope, user)
if err := sess.Create(); err != nil {
return nil, err
}
return sess, nil
}