db.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. "log"
  32. "time"
  33. common "git.semlanik.org/semlanik/gostfix/common"
  34. bcrypt "golang.org/x/crypto/bcrypt"
  35. bson "go.mongodb.org/mongo-driver/bson"
  36. mongo "go.mongodb.org/mongo-driver/mongo"
  37. options "go.mongodb.org/mongo-driver/mongo/options"
  38. config "git.semlanik.org/semlanik/gostfix/config"
  39. )
  40. type Storage struct {
  41. db *mongo.Database
  42. usersCollection *mongo.Collection
  43. tokensCollection *mongo.Collection
  44. emailsCollection *mongo.Collection
  45. allEmailsCollection *mongo.Collection
  46. mailsCollection *mongo.Collection
  47. }
  48. func qualifiedMailCollection(user string) string {
  49. sum := sha1.Sum([]byte(user))
  50. return "mb" + hex.EncodeToString(sum[:])
  51. }
  52. func NewStorage() (s *Storage, err error) {
  53. fullUrl := "mongodb://"
  54. if config.ConfigInstance().MongoUser != "" {
  55. fullUrl += config.ConfigInstance().MongoUser
  56. if config.ConfigInstance().MongoPassword != "" {
  57. fullUrl += ":" + config.ConfigInstance().MongoPassword
  58. }
  59. fullUrl += "@"
  60. }
  61. fullUrl += config.ConfigInstance().MongoAddress
  62. client, err := mongo.NewClient(options.Client().ApplyURI(fullUrl))
  63. if err != nil {
  64. return nil, err
  65. }
  66. ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
  67. defer cancel()
  68. err = client.Connect(ctx)
  69. if err != nil {
  70. return nil, err
  71. }
  72. db := client.Database("gostfix")
  73. index := mongo.IndexModel{
  74. Keys: bson.M{
  75. "user": 1,
  76. },
  77. Options: options.Index().SetUnique(true),
  78. }
  79. s = &Storage{
  80. db: db,
  81. usersCollection: db.Collection("users"),
  82. tokensCollection: db.Collection("tokens"),
  83. emailsCollection: db.Collection("emails"),
  84. allEmailsCollection: db.Collection("allEmails"),
  85. mailsCollection: db.Collection("mails"),
  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) RemoveMail(user string, m *common.Mail) error {
  231. return nil
  232. }
  233. func (s *Storage) MailList(user, email, folder string) ([]*common.MailMetadata, error) {
  234. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  235. cur, err := mailsCollection.Find(context.Background(), bson.M{"email": email})
  236. if err != nil {
  237. return nil, err
  238. }
  239. var headers []*common.MailMetadata
  240. for cur.Next(context.Background()) {
  241. result := &common.MailMetadata{}
  242. err = cur.Decode(result)
  243. if err != nil {
  244. log.Printf("Unable to read database mail record: %s", err)
  245. continue
  246. }
  247. log.Printf("Add message: %s", result.Id)
  248. headers = append(headers, result)
  249. }
  250. log.Printf("Mails read from database: %v", headers)
  251. return headers, nil
  252. }
  253. func (s *Storage) GetMail(user string, header *common.MailHeader) (m *common.Mail, err error) {
  254. return nil, nil
  255. }
  256. func (s *Storage) GetAttachment(user string, attachmentId string) (filePath string, err error) {
  257. return "", nil
  258. }
  259. func (s *Storage) GetUsers() (users []string, err error) {
  260. return nil, nil
  261. }
  262. func (s *Storage) GetEmails(user []string) (emails []string, err error) {
  263. return nil, nil
  264. }
  265. func (s *Storage) GetAllEmails() (emails []string, err error) {
  266. cur, err := s.allEmailsCollection.Find(context.Background(), bson.M{})
  267. if cur.Next(context.Background()) {
  268. result := struct {
  269. Emails []string
  270. }{}
  271. err = cur.Decode(&result)
  272. if err == nil {
  273. return result.Emails, nil
  274. }
  275. }
  276. return nil, err
  277. }