db.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. /*
  2. * MIT License
  3. *
  4. * Copyright (c) 2020 Alexey Edelev <semlanik@gmail.com>
  5. *
  6. * This file is part of gostfix project https://git.semlanik.org/semlanik/gostfix
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy of this
  9. * software and associated documentation files (the "Software"), to deal in the Software
  10. * without restriction, including without limitation the rights to use, copy, modify,
  11. * merge, publish, distribute, sublicense, and/or sell copies of the Software, and
  12. * to permit persons to whom the Software is furnished to do so, subject to the following
  13. * conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all copies
  16. * or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  19. * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  20. * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  21. * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  22. * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  23. * DEALINGS IN THE SOFTWARE.
  24. */
  25. package db
  26. import (
  27. "context"
  28. "crypto/sha1"
  29. "encoding/hex"
  30. "errors"
  31. "fmt"
  32. "log"
  33. "time"
  34. common "git.semlanik.org/semlanik/gostfix/common"
  35. bcrypt "golang.org/x/crypto/bcrypt"
  36. bson "go.mongodb.org/mongo-driver/bson"
  37. "go.mongodb.org/mongo-driver/bson/primitive"
  38. mongo "go.mongodb.org/mongo-driver/mongo"
  39. options "go.mongodb.org/mongo-driver/mongo/options"
  40. config "git.semlanik.org/semlanik/gostfix/config"
  41. )
  42. type Storage struct {
  43. db *mongo.Database
  44. usersCollection *mongo.Collection
  45. tokensCollection *mongo.Collection
  46. emailsCollection *mongo.Collection
  47. allEmailsCollection *mongo.Collection
  48. }
  49. func qualifiedMailCollection(user string) string {
  50. sum := sha1.Sum([]byte(user))
  51. return "mb" + hex.EncodeToString(sum[:])
  52. }
  53. func NewStorage() (s *Storage, err error) {
  54. fullUrl := "mongodb://"
  55. if config.ConfigInstance().MongoUser != "" {
  56. fullUrl += config.ConfigInstance().MongoUser
  57. if config.ConfigInstance().MongoPassword != "" {
  58. fullUrl += ":" + config.ConfigInstance().MongoPassword
  59. }
  60. fullUrl += "@"
  61. }
  62. fullUrl += config.ConfigInstance().MongoAddress
  63. client, err := mongo.NewClient(options.Client().ApplyURI(fullUrl))
  64. if err != nil {
  65. return nil, err
  66. }
  67. ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
  68. defer cancel()
  69. err = client.Connect(ctx)
  70. if err != nil {
  71. return nil, err
  72. }
  73. db := client.Database("gostfix")
  74. index := mongo.IndexModel{
  75. Keys: bson.M{
  76. "user": 1,
  77. },
  78. Options: options.Index().SetUnique(true),
  79. }
  80. s = &Storage{
  81. db: db,
  82. usersCollection: db.Collection("users"),
  83. tokensCollection: db.Collection("tokens"),
  84. emailsCollection: db.Collection("emails"),
  85. allEmailsCollection: db.Collection("allEmails"),
  86. }
  87. //Initial database setup
  88. s.usersCollection.Indexes().CreateOne(context.Background(), index)
  89. s.tokensCollection.Indexes().CreateOne(context.Background(), index)
  90. s.emailsCollection.Indexes().CreateOne(context.Background(), index)
  91. return
  92. }
  93. func (s *Storage) AddUser(user, password, fullName string) error {
  94. hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
  95. if err != nil {
  96. return err
  97. }
  98. hashString := string(hash)
  99. userInfo := bson.M{
  100. "user": user,
  101. "password": hashString,
  102. "fullName": fullName,
  103. }
  104. _, err = s.usersCollection.InsertOne(context.Background(), userInfo)
  105. if err != nil {
  106. return err
  107. }
  108. err = s.addEmail(user, user, true)
  109. if err != nil {
  110. s.usersCollection.DeleteOne(context.Background(), bson.M{"user": user})
  111. return err
  112. }
  113. //TODO: Update postfix virtual map here
  114. return nil
  115. }
  116. func (s *Storage) AddEmail(user string, email string) error {
  117. return s.addEmail(user, email, false)
  118. }
  119. func (s *Storage) addEmail(user string, email string, upsert bool) error {
  120. result := struct {
  121. User string
  122. }{}
  123. err := s.usersCollection.FindOne(context.Background(), bson.M{"user": user}).Decode(&result)
  124. if err != nil {
  125. return err
  126. }
  127. emails, err := s.GetAllEmails()
  128. if err != nil {
  129. return err
  130. }
  131. for _, existingEmail := range emails {
  132. if existingEmail == email {
  133. return errors.New("Email exists")
  134. }
  135. }
  136. _, err = s.emailsCollection.UpdateOne(context.Background(),
  137. bson.M{"user": user},
  138. bson.M{"$addToSet": bson.M{"email": email}},
  139. options.Update().SetUpsert(upsert))
  140. //TODO: Update postfix virtual map here
  141. return err
  142. }
  143. func (s *Storage) RemoveEmail(user string, email string) error {
  144. _, err := s.emailsCollection.UpdateOne(context.Background(),
  145. bson.M{"user": user},
  146. bson.M{"$pull": bson.M{"email": email}})
  147. //TODO: Update postfix virtual map here
  148. return err
  149. }
  150. func (s *Storage) CheckUser(user, password string) error {
  151. log.Printf("Check user: %s %s", user, password)
  152. result := struct {
  153. User string
  154. Password string
  155. }{}
  156. err := s.usersCollection.FindOne(context.Background(), bson.M{"user": user}).Decode(&result)
  157. if err != nil {
  158. return errors.New("Invalid user or password")
  159. }
  160. if bcrypt.CompareHashAndPassword([]byte(result.Password), []byte(password)) != nil {
  161. return errors.New("Invalid user or password")
  162. }
  163. return nil
  164. }
  165. func (s *Storage) AddToken(user, token string) error {
  166. log.Printf("Add token: %s\n", user)
  167. s.tokensCollection.UpdateOne(context.Background(),
  168. bson.M{"user": user},
  169. bson.M{
  170. "$addToSet": bson.M{
  171. "token": bson.M{
  172. "token": token,
  173. "expire": time.Now().Add(time.Hour * 24).Unix(),
  174. },
  175. },
  176. },
  177. options.Update().SetUpsert(true))
  178. s.CleanupTokens(user)
  179. return nil
  180. }
  181. func (s *Storage) CheckToken(user, token string) error {
  182. if token == "" {
  183. return errors.New("Invalid token")
  184. }
  185. cur, err := s.tokensCollection.Aggregate(context.Background(),
  186. bson.A{
  187. bson.M{"$match": bson.M{"user": user}},
  188. bson.M{"$unwind": "$token"},
  189. bson.M{"$match": bson.M{"token.token": token}},
  190. })
  191. if err != nil {
  192. log.Fatalln(err)
  193. return err
  194. }
  195. ok := false
  196. defer cur.Close(context.Background())
  197. if cur.Next(context.Background()) {
  198. result := struct {
  199. Token struct {
  200. Expire int64
  201. }
  202. }{}
  203. err = cur.Decode(&result)
  204. ok = err == nil && result.Token.Expire >= time.Now().Unix()
  205. }
  206. if ok {
  207. //TODO: Renew token
  208. return nil
  209. }
  210. return errors.New("Token expired")
  211. }
  212. func (s *Storage) RemoveToken(user, token string) error {
  213. s.CleanupTokens(user)
  214. _, err := s.tokensCollection.UpdateOne(context.Background(), bson.M{"user": user}, bson.M{"$pull": bson.M{"token": bson.M{"token": token}}})
  215. if err != nil {
  216. log.Printf("Unable to remove token %s", err)
  217. }
  218. return err
  219. }
  220. func (s *Storage) CleanupTokens(user string) {
  221. log.Printf("Cleanup tokens: %s\n", user)
  222. cur, err := s.tokensCollection.Aggregate(context.Background(),
  223. bson.A{
  224. bson.M{"$match": bson.M{"user": user}},
  225. bson.M{"$unwind": "$token"},
  226. })
  227. if err != nil {
  228. log.Fatalln(err)
  229. }
  230. type tokenMetadata struct {
  231. Expire int64
  232. Token string
  233. }
  234. tokensToKeep := bson.A{}
  235. defer cur.Close(context.Background())
  236. for cur.Next(context.Background()) {
  237. result := struct {
  238. Token *tokenMetadata
  239. }{
  240. Token: &tokenMetadata{},
  241. }
  242. err = cur.Decode(&result)
  243. if err == nil && result.Token.Expire >= time.Now().Unix() {
  244. tokensToKeep = append(tokensToKeep, result.Token)
  245. } else {
  246. log.Printf("Expired token found for %s : %d", user, result.Token.Expire)
  247. }
  248. }
  249. _, err = s.tokensCollection.UpdateOne(context.Background(), bson.M{"user": user}, bson.M{"$set": bson.M{"token": tokensToKeep}})
  250. return
  251. }
  252. func (s *Storage) SaveMail(email, folder string, m *common.Mail, read bool) error {
  253. result := &struct {
  254. User string
  255. }{}
  256. s.emailsCollection.FindOne(context.Background(), bson.M{"email": email}).Decode(result)
  257. mailsCollection := s.db.Collection(qualifiedMailCollection(result.User))
  258. mailsCollection.InsertOne(context.Background(), &struct {
  259. Email string
  260. Mail *common.Mail
  261. Folder string
  262. Read bool
  263. Trash bool
  264. }{
  265. Email: email,
  266. Mail: m,
  267. Folder: folder,
  268. Read: read,
  269. Trash: false,
  270. }, options.InsertOne().SetBypassDocumentValidation(true))
  271. return nil
  272. }
  273. func (s *Storage) MoveMail(user string, mailId string, folder string) error {
  274. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  275. oId, err := primitive.ObjectIDFromHex(mailId)
  276. if err != nil {
  277. return err
  278. }
  279. if folder == common.Trash {
  280. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": bson.M{"trash": true}})
  281. } else {
  282. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": bson.M{"folder": folder, "trash": false}})
  283. }
  284. return err
  285. }
  286. func (s *Storage) RestoreMail(user string, mailId string) error {
  287. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  288. oId, err := primitive.ObjectIDFromHex(mailId)
  289. if err != nil {
  290. return err
  291. }
  292. //TODO: Legacy for old databases remove soon
  293. metadata, err := s.GetMail(user, mailId)
  294. if metadata.Folder == common.Trash {
  295. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": bson.M{"folder": common.Inbox}})
  296. }
  297. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": bson.M{"trash": false}})
  298. return err
  299. }
  300. func (s *Storage) DeleteMail(user string, mailId string) error {
  301. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  302. oId, err := primitive.ObjectIDFromHex(mailId)
  303. if err != nil {
  304. return err
  305. }
  306. _, err = mailsCollection.DeleteOne(context.Background(), bson.M{"_id": oId})
  307. return err
  308. }
  309. func (s *Storage) GetMailList(user, email, folder string, frame common.Frame) ([]*common.MailMetadata, error) {
  310. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  311. matchFilter := bson.M{"email": email}
  312. if folder == common.Trash {
  313. matchFilter["$or"] = bson.A{
  314. bson.M{"trash": true},
  315. bson.M{"folder": folder}, //TODO: Legacy for old databases remove soon
  316. }
  317. } else {
  318. matchFilter["folder"] = folder
  319. matchFilter["$or"] = bson.A{
  320. bson.M{"trash": false},
  321. bson.M{"trash": bson.M{"$exists": false}}, //TODO: Legacy for old databases remove soon
  322. }
  323. }
  324. request := bson.A{
  325. bson.M{"$match": matchFilter},
  326. bson.M{"$sort": bson.M{"mail.header.date": -1}},
  327. }
  328. if frame.Skip > 0 {
  329. request = append(request, bson.M{"$skip": frame.Skip})
  330. }
  331. fmt.Printf("Trying limit number of mails: %v\n", frame)
  332. if frame.Limit > 0 {
  333. fmt.Printf("Limit number of mails: %v\n", frame)
  334. request = append(request, bson.M{"$limit": frame.Limit})
  335. }
  336. cur, err := mailsCollection.Aggregate(context.Background(), request)
  337. if err != nil {
  338. log.Println(err.Error())
  339. return nil, err
  340. }
  341. var headers []*common.MailMetadata
  342. for cur.Next(context.Background()) {
  343. result := &common.MailMetadata{}
  344. err = cur.Decode(result)
  345. if err != nil {
  346. log.Printf("Unable to read database mail record: %s", err)
  347. continue
  348. }
  349. // fmt.Printf("Add mail: %s", result.Id)
  350. headers = append(headers, result)
  351. }
  352. // fmt.Printf("Mails read from database: %v", headers)
  353. return headers, nil
  354. }
  355. func (s *Storage) GetUserInfo(user string) (*common.UserInfo, error) {
  356. result := &common.UserInfo{}
  357. err := s.usersCollection.FindOne(context.Background(), bson.M{"user": user}).Decode(result)
  358. return result, err
  359. }
  360. func (s *Storage) GetEmailStats(user string, email string, folder string) (unread, total int, err error) {
  361. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  362. result := &struct {
  363. Total int
  364. Unread int
  365. }{}
  366. matchFilter := bson.M{"email": email}
  367. if folder == common.Trash {
  368. matchFilter["$or"] = bson.A{
  369. bson.M{"trash": true},
  370. bson.M{"folder": folder}, //TODO: Legacy for old databases remove soon
  371. }
  372. } else {
  373. matchFilter["folder"] = folder
  374. matchFilter["$or"] = bson.A{
  375. bson.M{"trash": false},
  376. bson.M{"trash": bson.M{"$exists": false}}, //TODO: Legacy for old databases remove soon
  377. }
  378. }
  379. unreadMatchFilter := matchFilter
  380. unreadMatchFilter["read"] = false
  381. cur, err := mailsCollection.Aggregate(context.Background(), bson.A{bson.M{"$match": unreadMatchFilter}, bson.M{"$count": "unread"}})
  382. if err == nil && cur.Next(context.Background()) {
  383. cur.Decode(result)
  384. } else {
  385. return 0, 0, err
  386. }
  387. cur, err = mailsCollection.Aggregate(context.Background(), bson.A{bson.M{"$match": matchFilter}, bson.M{"$count": "total"}})
  388. if err == nil && cur.Next(context.Background()) {
  389. cur.Decode(result)
  390. } else {
  391. return 0, 0, err
  392. }
  393. return result.Unread, result.Total, err
  394. }
  395. func (s *Storage) GetMail(user string, id string) (metadata *common.MailMetadata, err error) {
  396. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  397. oId, err := primitive.ObjectIDFromHex(id)
  398. if err != nil {
  399. return nil, err
  400. }
  401. metadata = &common.MailMetadata{
  402. Mail: &common.Mail{},
  403. }
  404. err = mailsCollection.FindOne(context.Background(), bson.M{"_id": oId}).Decode(metadata)
  405. if err != nil {
  406. return nil, err
  407. }
  408. return metadata, nil
  409. }
  410. func (s *Storage) SetRead(user string, id string, read bool) error {
  411. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  412. oId, err := primitive.ObjectIDFromHex(id)
  413. if err != nil {
  414. return err
  415. }
  416. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": bson.M{"read": read}})
  417. return err
  418. }
  419. func (s *Storage) GetAttachment(user string, attachmentId string) (filePath string, err error) {
  420. return "", nil
  421. }
  422. func (s *Storage) GetUsers() (users []string, err error) {
  423. return nil, nil
  424. }
  425. func (s *Storage) GetEmails(user string) (emails []string, err error) {
  426. result := &struct {
  427. Email []string
  428. }{}
  429. err = s.emailsCollection.FindOne(context.Background(), bson.M{"user": user}).Decode(result)
  430. if err != nil {
  431. return nil, err
  432. }
  433. return result.Email, nil
  434. }
  435. func (s *Storage) GetAllEmails() (emails []string, err error) {
  436. cur, err := s.allEmailsCollection.Find(context.Background(), bson.M{})
  437. if cur.Next(context.Background()) {
  438. result := struct {
  439. Emails []string
  440. }{}
  441. err = cur.Decode(&result)
  442. if err == nil {
  443. return result.Emails, nil
  444. }
  445. }
  446. return nil, err
  447. }
  448. func (s *Storage) GetFolders(email string) (folders []*common.Folder) {
  449. folders = []*common.Folder{
  450. &common.Folder{Name: common.Inbox, Custom: false},
  451. &common.Folder{Name: common.Sent, Custom: false},
  452. &common.Folder{Name: common.Trash, Custom: false},
  453. &common.Folder{Name: common.Spam, Custom: false},
  454. }
  455. return
  456. }