1package webauth
2
3import (
4 "context"
5 "errors"
6
7 "github.com/mjl-/mox/mlog"
8 "github.com/mjl-/mox/store"
9)
10
11// AccountAuth is for user accounts, with username/password, and sessions stored in
12// memory and in the database with lifetimes that are automatically extended.
13var Accounts SessionAuth = accountSessionAuth{}
14
15type accountSessionAuth struct{}
16
17func (accountSessionAuth) login(ctx context.Context, log mlog.Log, username, password string) (bool, string, error) {
18 acc, err := store.OpenEmailAuth(log, username, password)
19 if err != nil && errors.Is(err, store.ErrUnknownCredentials) {
20 return false, "", nil
21 } else if err != nil {
22 return false, "", err
23 }
24 defer func() {
25 err := acc.Close()
26 log.Check(err, "closing account")
27 }()
28 return true, acc.Name, nil
29}
30
31func (accountSessionAuth) add(ctx context.Context, log mlog.Log, accountName string, loginAddress string) (sessionToken store.SessionToken, csrfToken store.CSRFToken, rerr error) {
32 return store.SessionAdd(ctx, log, accountName, loginAddress)
33}
34
35func (accountSessionAuth) use(ctx context.Context, log mlog.Log, accountName string, sessionToken store.SessionToken, csrfToken store.CSRFToken) (loginAddress string, rerr error) {
36 ls, err := store.SessionUse(ctx, log, accountName, sessionToken, csrfToken)
37 if err != nil {
38 return "", err
39 }
40 return ls.LoginAddress, nil
41}
42
43func (accountSessionAuth) remove(ctx context.Context, log mlog.Log, accountName string, sessionToken store.SessionToken) error {
44 return store.SessionRemove(ctx, log, accountName, sessionToken)
45}
46