db.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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) 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. }{
  264. Email: email,
  265. Mail: m,
  266. Folder: folder,
  267. Read: false,
  268. }, options.InsertOne().SetBypassDocumentValidation(true))
  269. return nil
  270. }
  271. func (s *Storage) MoveMail(user string, mailId string, folder string) error {
  272. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  273. oId, err := primitive.ObjectIDFromHex(mailId)
  274. if err != nil {
  275. return err
  276. }
  277. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": bson.M{"folder": folder}})
  278. return err
  279. }
  280. func (s *Storage) DeleteMail(user string, mailId string) error {
  281. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  282. oId, err := primitive.ObjectIDFromHex(mailId)
  283. if err != nil {
  284. return err
  285. }
  286. _, err = mailsCollection.DeleteOne(context.Background(), bson.M{"_id": oId})
  287. return err
  288. }
  289. func (s *Storage) MailList(user, email, folder string, frame common.Frame) ([]*common.MailMetadata, error) {
  290. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  291. request := bson.A{
  292. bson.M{"$match": bson.M{"email": email, "folder": folder}},
  293. bson.M{"$sort": bson.M{"mail.header.date": -1}},
  294. }
  295. if frame.Skip > 0 {
  296. request = append(request, bson.M{"$skip": frame.Skip})
  297. }
  298. fmt.Printf("Trying limit number of mails: %v\n", frame)
  299. if frame.Limit > 0 {
  300. fmt.Printf("Limit number of mails: %v\n", frame)
  301. request = append(request, bson.M{"$limit": frame.Limit})
  302. }
  303. cur, err := mailsCollection.Aggregate(context.Background(), request)
  304. if err != nil {
  305. return nil, err
  306. }
  307. var headers []*common.MailMetadata
  308. for cur.Next(context.Background()) {
  309. result := &common.MailMetadata{}
  310. err = cur.Decode(result)
  311. if err != nil {
  312. log.Printf("Unable to read database mail record: %s", err)
  313. continue
  314. }
  315. // fmt.Printf("Add mail: %s", result.Id)
  316. headers = append(headers, result)
  317. }
  318. // fmt.Printf("Mails read from database: %v", headers)
  319. return headers, nil
  320. }
  321. func (s *Storage) GetUserInfo(user string) (*common.UserInfo, error) {
  322. result := &common.UserInfo{}
  323. err := s.usersCollection.FindOne(context.Background(), bson.M{"user": user}).Decode(result)
  324. return result, err
  325. }
  326. func (s *Storage) GetEmailStats(user string, email string, folder string) (unread, total int, err error) {
  327. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  328. result := &struct {
  329. Total int
  330. Unread int
  331. }{}
  332. cur, err := mailsCollection.Aggregate(context.Background(), bson.A{bson.M{"$match": bson.M{"email": email, "folder": folder, "read": false}}, bson.M{"$count": "unread"}})
  333. if err == nil && cur.Next(context.Background()) {
  334. cur.Decode(result)
  335. } else {
  336. return 0, 0, err
  337. }
  338. cur, err = mailsCollection.Aggregate(context.Background(), bson.A{bson.M{"$match": bson.M{"email": email, "folder": folder}}, bson.M{"$count": "total"}})
  339. if err == nil && cur.Next(context.Background()) {
  340. cur.Decode(result)
  341. } else {
  342. return 0, 0, err
  343. }
  344. return result.Unread, result.Total, err
  345. }
  346. func (s *Storage) GetMail(user string, id string) (m *common.Mail, err error) {
  347. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  348. oId, err := primitive.ObjectIDFromHex(id)
  349. if err != nil {
  350. return nil, err
  351. }
  352. m = &common.Mail{}
  353. result := &struct {
  354. Mail *common.Mail
  355. }{
  356. Mail: m,
  357. }
  358. err = mailsCollection.FindOne(context.Background(), bson.M{"_id": oId}).Decode(result)
  359. if err != nil {
  360. return nil, err
  361. }
  362. return result.Mail, nil
  363. }
  364. func (s *Storage) SetRead(user string, id string, read bool) error {
  365. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  366. oId, err := primitive.ObjectIDFromHex(id)
  367. if err != nil {
  368. return err
  369. }
  370. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": bson.M{"read": read}})
  371. return err
  372. }
  373. func (s *Storage) GetAttachment(user string, attachmentId string) (filePath string, err error) {
  374. return "", nil
  375. }
  376. func (s *Storage) GetUsers() (users []string, err error) {
  377. return nil, nil
  378. }
  379. func (s *Storage) GetEmails(user string) (emails []string, err error) {
  380. result := &struct {
  381. Email []string
  382. }{}
  383. err = s.emailsCollection.FindOne(context.Background(), bson.M{"user": user}).Decode(result)
  384. if err != nil {
  385. return nil, err
  386. }
  387. return result.Email, nil
  388. }
  389. func (s *Storage) GetAllEmails() (emails []string, err error) {
  390. cur, err := s.allEmailsCollection.Find(context.Background(), bson.M{})
  391. if cur.Next(context.Background()) {
  392. result := struct {
  393. Emails []string
  394. }{}
  395. err = cur.Decode(&result)
  396. if err == nil {
  397. return result.Emails, nil
  398. }
  399. }
  400. return nil, err
  401. }
  402. func (s *Storage) GetFolders(email string) (folders []*common.Folder) {
  403. folders = []*common.Folder{
  404. &common.Folder{Name: common.Inbox, Custom: false},
  405. &common.Folder{Name: common.Trash, Custom: false},
  406. &common.Folder{Name: common.Spam, Custom: false},
  407. }
  408. return
  409. }