authenticator.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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 auth
  26. import (
  27. "context"
  28. "errors"
  29. "log"
  30. "time"
  31. "git.semlanik.org/semlanik/gostfix/config"
  32. utils "git.semlanik.org/semlanik/gostfix/utils"
  33. uuid "github.com/google/uuid"
  34. "go.mongodb.org/mongo-driver/bson"
  35. "go.mongodb.org/mongo-driver/mongo"
  36. "go.mongodb.org/mongo-driver/mongo/options"
  37. "golang.org/x/crypto/bcrypt"
  38. )
  39. type Authenticator struct {
  40. db *mongo.Database
  41. usersCollection *mongo.Collection
  42. tokensCollection *mongo.Collection
  43. }
  44. type Privileges int
  45. const (
  46. AdminPrivilege = 1 << iota
  47. SendMailPrivilege
  48. )
  49. func NewAuthenticator() (*Authenticator, error) {
  50. fullUrl := "mongodb://"
  51. if config.ConfigInstance().MongoUser != "" {
  52. fullUrl += config.ConfigInstance().MongoUser
  53. if config.ConfigInstance().MongoPassword != "" {
  54. fullUrl += ":" + config.ConfigInstance().MongoPassword
  55. }
  56. fullUrl += "@"
  57. }
  58. fullUrl += config.ConfigInstance().MongoAddress
  59. client, err := mongo.NewClient(options.Client().ApplyURI(fullUrl))
  60. if err != nil {
  61. return nil, err
  62. }
  63. ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
  64. defer cancel()
  65. err = client.Connect(ctx)
  66. if err != nil {
  67. return nil, err
  68. }
  69. db := client.Database("gostfix")
  70. a := &Authenticator{
  71. db: db,
  72. usersCollection: db.Collection("users"),
  73. tokensCollection: db.Collection("tokens"),
  74. }
  75. return a, nil
  76. }
  77. func (a *Authenticator) CheckUser(user, password string) error {
  78. log.Printf("Check user: %s", user)
  79. result := struct {
  80. User string
  81. Password string
  82. }{}
  83. err := a.usersCollection.FindOne(context.Background(), bson.M{"user": user}).Decode(&result)
  84. if err != nil {
  85. return errors.New("Invalid user or password")
  86. }
  87. if bcrypt.CompareHashAndPassword([]byte(result.Password), []byte(password)) != nil {
  88. return errors.New("Invalid user or password")
  89. }
  90. return nil
  91. }
  92. func (a *Authenticator) addToken(user, token string) error {
  93. log.Printf("Add token: %s\n", user)
  94. a.tokensCollection.UpdateOne(context.Background(),
  95. bson.M{"user": user},
  96. bson.M{
  97. "$addToSet": bson.M{
  98. "token": bson.M{
  99. "token": token,
  100. "expire": time.Now().Add(time.Hour * 24).Unix(),
  101. },
  102. },
  103. },
  104. options.Update().SetUpsert(true))
  105. a.cleanupTokens(user)
  106. return nil
  107. }
  108. func (a *Authenticator) cleanupTokens(user string) {
  109. log.Printf("Cleanup tokens: %s\n", user)
  110. cur, err := a.tokensCollection.Aggregate(context.Background(),
  111. bson.A{
  112. bson.M{"$match": bson.M{"user": user}},
  113. bson.M{"$unwind": "$token"},
  114. })
  115. if err != nil {
  116. log.Fatalln(err)
  117. }
  118. type tokenMetadata struct {
  119. Expire int64
  120. Token string
  121. }
  122. tokensToKeep := bson.A{}
  123. defer cur.Close(context.Background())
  124. for cur.Next(context.Background()) {
  125. result := struct {
  126. Token *tokenMetadata
  127. }{
  128. Token: &tokenMetadata{},
  129. }
  130. err = cur.Decode(&result)
  131. if err == nil && result.Token.Expire >= time.Now().Unix() {
  132. tokensToKeep = append(tokensToKeep, result.Token)
  133. } else {
  134. log.Printf("Expired token found for %s : %d", user, result.Token.Expire)
  135. }
  136. }
  137. _, err = a.tokensCollection.UpdateOne(context.Background(), bson.M{"user": user}, bson.M{"$set": bson.M{"token": tokensToKeep}})
  138. return
  139. }
  140. func (a *Authenticator) Login(user, password string) (string, bool) {
  141. if !utils.RegExpUtilsInstance().EmailChecker.MatchString(user) {
  142. return "", false
  143. }
  144. if a.CheckUser(user, password) != nil {
  145. return "", false
  146. }
  147. token := uuid.New().String()
  148. a.addToken(user, token)
  149. return token, true
  150. }
  151. func (a *Authenticator) Logout(user, token string) error {
  152. a.cleanupTokens(user)
  153. _, err := a.tokensCollection.UpdateOne(context.Background(), bson.M{"user": user}, bson.M{"$pull": bson.M{"token": bson.M{"token": token}}})
  154. if err != nil {
  155. log.Printf("Unable to remove token %s", err)
  156. }
  157. return err
  158. }
  159. func (a *Authenticator) checkToken(user, token string) error {
  160. if token == "" {
  161. return errors.New("Invalid token")
  162. }
  163. cur, err := a.tokensCollection.Aggregate(context.Background(),
  164. bson.A{
  165. bson.M{"$match": bson.M{"user": user}},
  166. bson.M{"$unwind": "$token"},
  167. bson.M{"$match": bson.M{"token.token": token}},
  168. })
  169. if err != nil {
  170. log.Fatalln(err)
  171. return err
  172. }
  173. ok := false
  174. defer cur.Close(context.Background())
  175. if cur.Next(context.Background()) {
  176. result := struct {
  177. Token struct {
  178. Expire int64
  179. }
  180. }{}
  181. err = cur.Decode(&result)
  182. ok = err == nil && (config.ConfigInstance().WebSessionExpireTime <= 0 || result.Token.Expire >= time.Now().Unix())
  183. }
  184. if ok {
  185. if config.ConfigInstance().WebSessionExpireTime > 0 {
  186. opts := options.Update().SetArrayFilters(options.ArrayFilters{
  187. Registry: bson.DefaultRegistry,
  188. Filters: bson.A{
  189. bson.M{"element.token": token},
  190. }})
  191. a.tokensCollection.UpdateOne(context.Background(),
  192. bson.M{
  193. "user": user,
  194. },
  195. bson.M{
  196. "$set": bson.M{
  197. "token.$[element].expire": time.Now().Add(config.ConfigInstance().WebSessionExpireTime).Unix(),
  198. },
  199. },
  200. opts)
  201. }
  202. return nil
  203. }
  204. return errors.New("Token expired")
  205. }
  206. func (a *Authenticator) Verify(user, token string) bool {
  207. if !utils.RegExpUtilsInstance().EmailChecker.MatchString(user) {
  208. return false
  209. }
  210. return a.checkToken(user, token) == nil
  211. }
  212. func (a *Authenticator) CheckPrivileges(user string, privilege Privileges) {
  213. }