73 lines
1.9 KiB
Go
Raw Normal View History

2021-07-18 23:03:28 +01:00
/*
* Copyright (c) 2021 Neil Alexander
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
2021-07-07 18:15:07 +01:00
package imapserver
import (
2021-07-09 00:26:43 +01:00
"encoding/hex"
2021-07-07 18:15:07 +01:00
"fmt"
"log"
"github.com/emersion/go-imap"
"github.com/emersion/go-imap/backend"
"github.com/neilalexander/yggmail/internal/config"
"github.com/neilalexander/yggmail/internal/storage"
2021-07-08 23:12:20 +01:00
"github.com/neilalexander/yggmail/internal/utils"
2021-07-07 18:15:07 +01:00
)
type Backend struct {
Config *config.Config
Log *log.Logger
Storage storage.Storage
Server *IMAPServer
2021-07-07 18:15:07 +01:00
}
func (b *Backend) Login(conn *imap.ConnInfo, username, password string) (backend.User, error) {
2021-07-08 23:12:20 +01:00
// If our username is email-like, then take just the localpart
2021-07-09 00:08:26 +01:00
if pk, err := utils.ParseAddress(username); err == nil {
if !pk.Equal(b.Config.PublicKey) {
b.Log.Println("Failed to authenticate IMAP user due to wrong domain", pk, b.Config.PublicKey)
2021-07-08 23:12:20 +01:00
return nil, fmt.Errorf("failed to authenticate: wrong domain in username")
}
}
2021-07-09 00:26:43 +01:00
username = hex.EncodeToString(b.Config.PublicKey)
2021-07-09 00:08:26 +01:00
if authed, err := b.Storage.ConfigTryPassword(password); err != nil {
2021-07-07 18:15:07 +01:00
b.Log.Printf("Failed to authenticate IMAP user %q due to error: %s", username, err)
return nil, fmt.Errorf("failed to authenticate: %w", err)
} else if !authed {
b.Log.Printf("Failed to authenticate IMAP user %q\n", username)
return nil, backend.ErrInvalidCredentials
}
defer b.Log.Printf("Authenticated IMAP user from %s as %q\n", conn.RemoteAddr.String(), username)
2021-07-07 18:15:07 +01:00
user := &User{
backend: b,
username: username,
conn: conn,
2021-07-07 18:15:07 +01:00
}
return user, nil
}
/*
func (b *Backend) NotifyNew(id int) error {
b.Server.server.ForEachConn(func(conn server.Conn) {
notify := false
for _, cap := range conn.Capabilities() {
if cap == "NOTIFY" {
notify = true
}
}
if !notify {
return
}
conn.WaitReady()
conn.WriteResp()
})
return nil
}
*/