-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbackend.go
More file actions
109 lines (91 loc) · 2.52 KB
/
backend.go
File metadata and controls
109 lines (91 loc) · 2.52 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package imapmaildir
import (
"errors"
"io/ioutil"
"log"
"os"
"strings"
"sync"
"github.com/asdine/storm/v3"
"github.com/emersion/go-imap"
"github.com/emersion/go-imap/backend"
)
type Backend struct {
Log *log.Logger
Debug *log.Logger
PathTemplate string
Authenticator func(*imap.ConnInfo, string, string) (bool, error)
// BoltDB does not allow to open the same database file multiple times,
// therefore we need to serialize access to one handle and close it only if
// the mailbox is no longer used.
//
// dbsLock protects the concurrent map access. At the moment there is no
// clever locking and dbsLock is held for the whole duration of storm.DB
// initialization. That is, once dbsLock is acquired, all elements in the
// map have vaild db.
//
// Lookup key is username + \0 + mailboxName.
dbs map[string]mailboxHandle
dbsLock sync.Mutex
}
type mailboxHandle struct {
db *storm.DB
uses int64
}
func (b *Backend) Login(connInfo *imap.ConnInfo, username, password string) (backend.User, error) {
if b.Authenticator != nil {
ok, err := b.Authenticator(connInfo, username, password)
if err != nil || !ok {
if err != nil {
b.Log.Printf("authentication error: %v", err)
}
return nil, backend.ErrInvalidCredentials
}
}
return b.GetUser(username)
}
func (b *Backend) GetUser(username string) (backend.User, error) {
basePath := strings.ReplaceAll(b.PathTemplate, "{username}", username)
if _, err := os.Stat(basePath); err != nil {
if os.IsNotExist(err) {
return nil, backend.ErrInvalidCredentials
}
b.Log.Printf("%v", err)
return nil, errors.New("I/O error")
}
b.Debug.Printf("user logged in (%v, %v)", username, basePath)
return &User{
b: b,
name: username,
basePath: basePath,
}, nil
}
func (b *Backend) CreateUser(username string) error {
basePath := strings.ReplaceAll(b.PathTemplate, "{username}", username)
err := os.Mkdir(basePath, 0700)
if err != nil {
if os.IsExist(err) {
return errors.New("imapmaildir: user already exits")
}
return err
}
return nil
}
func (b *Backend) Close() error {
b.dbsLock.Lock()
defer b.dbsLock.Unlock()
for k, db := range b.dbs {
if err := db.db.Close(); err != nil {
b.Log.Printf("close failed for %s DB: %v", k, err)
}
}
return nil
}
func New(pathTemplate string) (*Backend, error) {
return &Backend{
Log: log.New(os.Stderr, "imapmaildir: ", 0),
Debug: log.New(ioutil.Discard, "imapmaildir[debug]: ", 0),
PathTemplate: pathTemplate,
dbs: map[string]mailboxHandle{},
}, nil
}