-
Notifications
You must be signed in to change notification settings - Fork 0
/
token_repo_impl.go
98 lines (77 loc) · 2.33 KB
/
token_repo_impl.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package token
import (
"context"
"fmt"
"myschool/pkg/model"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
)
const TokenCollectionName string = "token"
// implmentation of AuthTokenModel
type AuthToken struct {
ID string `json:"id,omitempty" bson:"_id,omitempty"`
Token string `json:"token,omitempty" bson:"token,omitempty"`
UserID string `json:"userId,omitempty" bson:"userId,omitempty"`
Email string `json:"email,omitempty" bson:"email,omitempty"`
Expiry int `json:"expiry,omitempty" bson:"expiry,omitempty"`
}
// Safe checker to know if this file already implements the model interface correctly or not
var _ (model.AuthTokenModel) = (*AuthToken)(nil)
func (s *AuthToken) GetID() string {
return s.ID
}
func (s *AuthToken) GetToken() string {
return s.Token
}
func (s *AuthToken) GetUserID() string {
return s.UserID
}
func (s *AuthToken) GetEmail() string {
return s.Email
}
func (s *AuthToken) GetExpiry() int {
return s.Expiry
}
// unexportable
type repoPrivate struct {
db *mongo.Database
}
// Safe checker to know if this file already implements the interface correctly or not
var _ (model.AuthTokenRepo) = (*repoPrivate)(nil)
func NewRepo(db *mongo.Database) model.AuthTokenRepo {
return &repoPrivate{
db: db,
}
}
func (repo *repoPrivate) Create(ctx context.Context, args model.TokenCreationParam) (model.AuthTokenModel, error) {
newDocument := &AuthToken{
Token: args.Token,
UserID: args.UserID,
Email: args.Email,
Expiry: args.Expiry,
}
res, err := repo.db.Collection(TokenCollectionName).InsertOne(ctx, newDocument)
if err != nil {
return nil, err
}
newDocument.ID = res.InsertedID.(primitive.ObjectID).Hex()
return newDocument, nil
}
func (repo *repoPrivate) Find(ctx context.Context, token string) (model.AuthTokenModel, error) {
result := repo.db.Collection(TokenCollectionName).FindOne(context.Background(), bson.M{"token": token})
var doc AuthToken
result.Decode(&doc)
return &doc, result.Err()
}
func (repo *repoPrivate) Delete(ctx context.Context, token string) error {
filter := bson.M{"token": token}
result, err := repo.db.Collection(TokenCollectionName).DeleteOne(context.Background(), filter)
if err != nil {
return err
}
if result.DeletedCount < 1 {
return fmt.Errorf("the token is not found")
}
return nil
}