/
backend.go
82 lines (67 loc) · 1.74 KB
/
backend.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package notmuch
import (
"fmt"
"sync"
"github.com/sirupsen/logrus"
"github.com/stbenjam/go-imap-notmuch/pkg/uid"
"github.com/emersion/go-imap"
"github.com/emersion/go-imap/backend"
notmuch "github.com/zenhack/go.notmuch"
"golang.org/x/crypto/bcrypt"
"github.com/stbenjam/go-imap-notmuch/pkg/config"
)
type Backend struct {
user *User
uidMapper *uid.Mapper
}
func (b *Backend) Login(_ *imap.ConnInfo, username, password string) (backend.User, error) {
err := bcrypt.CompareHashAndPassword([]byte(b.user.password), []byte(password))
if err != nil {
logrus.WithError(err).Errorf("couldn't compare hash and password")
}
if err == nil && username == b.user.username {
return b.user, nil
}
return nil, fmt.Errorf("invalid username or password")
}
func New(cfg *config.Config) (*Backend, error) {
db, err := notmuch.Open(cfg.Maildir, notmuch.DBReadWrite)
if err != nil {
return nil, err
}
db.Close()
uidMapper, err := uid.New(cfg.UidDatabase)
if err != nil {
return nil, fmt.Errorf("couldn't open uid database: %w", err)
}
user := &User{
username: cfg.Username,
password: cfg.Password,
}
// Parse mailbox list from config file
mailboxes := make(map[string]*Mailbox)
for _, mailbox := range cfg.Mailboxes {
attrs := make([]string, 0)
for _, attr := range mailbox.Attributes {
if attr[0] != '\\' {
attrs = append(attrs, "\\"+attr)
} else {
attrs = append(attrs, attr)
}
}
mailboxes[mailbox.Name] = &Mailbox{
name: mailbox.Name,
query: mailbox.Query,
maildir: cfg.Maildir,
attributes: attrs,
user: user,
lock: &sync.RWMutex{},
uidMapper: uidMapper,
}
}
user.mailboxes = mailboxes
return &Backend{
user: user,
uidMapper: uidMapper,
}, nil
}