authenticator.go 6.8 KB

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