/
token.go
59 lines (48 loc) · 1.27 KB
/
token.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
package store
import (
"context"
"log"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"github.com/miyuki-starmiya/go-oauth2-server/db/model"
)
func NewTokenStore(db *mongo.Database) *TokenStore {
return &TokenStore{
DB: db,
}
}
type TokenStore struct {
DB *mongo.Database
}
func (ts *TokenStore) CreateData(data *model.TokenData) error {
collection := ts.DB.Collection("tokens")
// Insert a single document
insertResult, err := collection.InsertOne(context.TODO(), data)
if err != nil {
log.Printf("Error: %v\n", err)
return err
}
log.Printf("Inserted a single document: %v\n", insertResult.InsertedID)
return nil
}
func (ts *TokenStore) GetData(clientId string, accessToken string) (*model.TokenData, error) {
collection := ts.DB.Collection("tokens")
// Define the filter criteria
filter := bson.M{
"client_id": clientId,
"access_token": accessToken,
}
var result *model.TokenData
err := collection.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
if err == mongo.ErrNoDocuments {
log.Println("No document was found with the given params")
} else {
log.Printf("Error: %v\n", err)
}
return nil, err
}
// Print the found document
log.Printf("Found a document: %+v\n", result)
return result, nil
}