db.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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, %s", user, token)
  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 * 96).Unix(),
  174. },
  175. },
  176. },
  177. options.Update().SetUpsert(true))
  178. return nil
  179. }
  180. func (s *Storage) CheckToken(user, token string) error {
  181. log.Printf("Check token: %s %s", user, token)
  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. bson.M{"$project": bson.M{"_id": 0, "token.expire": 1}},
  191. })
  192. if err != nil {
  193. log.Fatalln(err)
  194. return err
  195. }
  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. if err == nil && result.Token.Expire >= time.Now().Unix() {
  205. log.Printf("Check token %s expire: %d", user, result.Token.Expire)
  206. return nil
  207. }
  208. }
  209. return errors.New("Token expired")
  210. }
  211. func (s *Storage) SaveMail(email, folder string, m *common.Mail) error {
  212. result := &struct {
  213. User string
  214. }{}
  215. s.emailsCollection.FindOne(context.Background(), bson.M{"email": email}).Decode(result)
  216. mailsCollection := s.db.Collection(qualifiedMailCollection(result.User))
  217. mailsCollection.InsertOne(context.Background(), &struct {
  218. Email string
  219. Mail *common.Mail
  220. Folder string
  221. Read bool
  222. }{
  223. Email: email,
  224. Mail: m,
  225. Folder: folder,
  226. Read: false,
  227. }, options.InsertOne().SetBypassDocumentValidation(true))
  228. return nil
  229. }
  230. func (s *Storage) MoveMail(user string, mailId string, folder string) error {
  231. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  232. oId, err := primitive.ObjectIDFromHex(mailId)
  233. if err != nil {
  234. return err
  235. }
  236. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": bson.M{"folder": folder}})
  237. return err
  238. }
  239. func (s *Storage) DeleteMail(user string, mailId string) error {
  240. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  241. oId, err := primitive.ObjectIDFromHex(mailId)
  242. if err != nil {
  243. return err
  244. }
  245. _, err = mailsCollection.DeleteOne(context.Background(), bson.M{"_id": oId})
  246. return err
  247. }
  248. func (s *Storage) MailList(user, email, folder string, frame common.Frame) ([]*common.MailMetadata, error) {
  249. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  250. request := bson.A{
  251. bson.M{"$match": bson.M{"email": email, "folder": folder}},
  252. bson.M{"$sort": bson.M{"mail.header.date": 1}},
  253. }
  254. if frame.Skip > 0 {
  255. request = append(request, bson.M{"$skip": frame.Skip})
  256. }
  257. fmt.Printf("Trying limit number of mails: %v\n", frame)
  258. if frame.Limit > 0 {
  259. fmt.Printf("Limit number of mails: %v\n", frame)
  260. request = append(request, bson.M{"$limit": frame.Limit})
  261. }
  262. cur, err := mailsCollection.Aggregate(context.Background(), request)
  263. if err != nil {
  264. return nil, err
  265. }
  266. var headers []*common.MailMetadata
  267. for cur.Next(context.Background()) {
  268. result := &common.MailMetadata{}
  269. err = cur.Decode(result)
  270. if err != nil {
  271. log.Printf("Unable to read database mail record: %s", err)
  272. continue
  273. }
  274. // fmt.Printf("Add mail: %s", result.Id)
  275. headers = append(headers, result)
  276. }
  277. // fmt.Printf("Mails read from database: %v", headers)
  278. return headers, nil
  279. }
  280. func (s *Storage) GetUserInfo(user string) (*common.UserInfo, error) {
  281. result := &common.UserInfo{}
  282. err := s.usersCollection.FindOne(context.Background(), bson.M{"user": user}).Decode(result)
  283. return result, err
  284. }
  285. func (s *Storage) GetEmailStats(user string, email string, folder string) (unread, total int, err error) {
  286. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  287. result := &struct {
  288. Total int
  289. Unread int
  290. }{}
  291. cur, err := mailsCollection.Aggregate(context.Background(), bson.A{bson.M{"$match": bson.M{"email": email, "folder": folder, "read": false}}, bson.M{"$count": "unread"}})
  292. if err == nil && cur.Next(context.Background()) {
  293. cur.Decode(result)
  294. } else {
  295. return 0, 0, err
  296. }
  297. cur, err = mailsCollection.Aggregate(context.Background(), bson.A{bson.M{"$match": bson.M{"email": email, "folder": folder}}, bson.M{"$count": "total"}})
  298. if err == nil && cur.Next(context.Background()) {
  299. cur.Decode(result)
  300. } else {
  301. return 0, 0, err
  302. }
  303. return result.Unread, result.Total, err
  304. }
  305. func (s *Storage) GetMail(user string, id string) (m *common.Mail, err error) {
  306. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  307. oId, err := primitive.ObjectIDFromHex(id)
  308. if err != nil {
  309. return nil, err
  310. }
  311. m = &common.Mail{}
  312. result := &struct {
  313. Mail *common.Mail
  314. }{
  315. Mail: m,
  316. }
  317. err = mailsCollection.FindOne(context.Background(), bson.M{"_id": oId}).Decode(result)
  318. if err != nil {
  319. return nil, err
  320. }
  321. return result.Mail, nil
  322. }
  323. func (s *Storage) SetRead(user string, id string, read bool) error {
  324. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  325. oId, err := primitive.ObjectIDFromHex(id)
  326. if err != nil {
  327. return err
  328. }
  329. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": bson.M{"read": read}})
  330. return err
  331. }
  332. func (s *Storage) GetAttachment(user string, attachmentId string) (filePath string, err error) {
  333. return "", nil
  334. }
  335. func (s *Storage) GetUsers() (users []string, err error) {
  336. return nil, nil
  337. }
  338. func (s *Storage) GetEmails(user string) (emails []string, err error) {
  339. fmt.Printf("user: %s\n", user)
  340. result := &struct {
  341. Email []string
  342. }{}
  343. err = s.emailsCollection.FindOne(context.Background(), bson.M{"user": user}).Decode(result)
  344. if err != nil {
  345. return nil, err
  346. }
  347. return result.Email, nil
  348. }
  349. func (s *Storage) GetAllEmails() (emails []string, err error) {
  350. cur, err := s.allEmailsCollection.Find(context.Background(), bson.M{})
  351. if cur.Next(context.Background()) {
  352. result := struct {
  353. Emails []string
  354. }{}
  355. err = cur.Decode(&result)
  356. if err == nil {
  357. return result.Emails, nil
  358. }
  359. }
  360. return nil, err
  361. }
  362. func (s *Storage) GetFolders(email string) (folders []*common.Folder) {
  363. folders = []*common.Folder{
  364. &common.Folder{Name: common.Inbox, Custom: false},
  365. &common.Folder{Name: common.Trash, Custom: false},
  366. &common.Folder{Name: common.Spam, Custom: false},
  367. }
  368. return
  369. }