sum7
/
yaja
Archived
1
0
Fork 0
This repository has been archived on 2020-09-27. You can view files and clone it, but cannot push or open issues or pull requests.
yaja/database/main.go

86 lines
1.7 KiB
Go
Raw Normal View History

2017-12-14 21:30:07 +01:00
package database
import (
"errors"
"sync"
log "github.com/sirupsen/logrus"
"dev.sum7.eu/genofire/yaja/model"
"dev.sum7.eu/genofire/yaja/xmpp/base"
2017-12-14 21:30:07 +01:00
)
type State struct {
Domains map[string]*model.Domain `json:"domains"`
sync.Mutex
}
func (s *State) AddAccount(a *model.Account) error {
2018-02-15 22:03:49 +01:00
if a.Local == "" {
2017-12-14 21:30:07 +01:00
return errors.New("No localpart exists in account")
}
if d := a.Domain; d != nil {
if d.FQDN == "" {
return errors.New("No fqdn exists in domain")
}
s.Lock()
domain, ok := s.Domains[d.FQDN]
if !ok {
if s.Domains == nil {
s.Domains = make(map[string]*model.Domain)
}
s.Domains[d.FQDN] = d
domain = d
}
s.Unlock()
domain.Lock()
defer domain.Unlock()
if domain.Accounts == nil {
domain.Accounts = make(map[string]*model.Account)
}
2018-02-15 22:03:49 +01:00
_, ok = domain.Accounts[a.Local]
2017-12-14 21:30:07 +01:00
if ok {
return errors.New("exists already")
}
2018-02-15 22:03:49 +01:00
domain.Accounts[a.Local] = a
2017-12-14 21:30:07 +01:00
a.Domain = d
return nil
}
return errors.New("no give domain")
}
func (s *State) Authenticate(jid *xmppbase.JID, password string) (bool, error) {
2017-12-14 21:30:07 +01:00
logger := log.WithField("database", "auth")
if domain, ok := s.Domains[jid.Domain]; ok {
2018-02-15 22:03:49 +01:00
if acc, ok := domain.Accounts[jid.Local]; ok {
2017-12-14 21:30:07 +01:00
if acc.ValidatePassword(password) {
return true, nil
} else {
logger.Debug("password not valid")
}
} else {
logger.Debug("account not found")
}
} else {
logger.Debug("domain not found")
}
return false, nil
}
func (s *State) GetAccount(jid *xmppbase.JID) *model.Account {
logger := log.WithField("database", "get")
if domain, ok := s.Domains[jid.Domain]; ok {
2018-02-15 22:03:49 +01:00
if acc, ok := domain.Accounts[jid.Local]; ok {
return acc
} else {
logger.Debug("account not found")
}
} else {
logger.Debug("domain not found")
}
return nil
}