/
mongo.go
119 lines (97 loc) · 2.55 KB
/
mongo.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package drivers
import (
"context"
"encoding/json"
"errors"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"simpaix.net/simpa/v2/engine/crypt"
"simpaix.net/simpa/v2/engine/sessions"
)
type MongoStore struct {
*mongo.Collection
timeout time.Duration
crypt crypt.CrypterI
}
// Creates new mongo storage
func NewMongoStore(col *mongo.Collection, timeout time.Duration, crypt crypt.CrypterI) *MongoStore {
return &MongoStore{col, timeout, crypt}
}
// Saves session back to the store. Encrypts the [session.values] object.
func (s *MongoStore) Set(sess *sessions.Session) error {
obj_id, err := primitive.ObjectIDFromHex(sess.ID)
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*s.timeout)
defer cancel()
raw, err := json.Marshal(sess.Values)
if err != nil {
return err
}
opts, err := json.Marshal(sess.Opts)
if err != nil {
return err
}
enc_raw, err := s.crypt.Encrypt(string(raw))
if err != nil {
return err
}
if err := s.Collection.FindOneAndUpdate(ctx, bson.M{
"_id": obj_id,
}, bson.M{
"$set": bson.D{
{Key: "values", Value: string(enc_raw)},
{Key: "options", Value: string(opts)},
},
}, options.FindOneAndUpdate().SetUpsert(true)).Err(); err != nil && err != mongo.ErrNoDocuments {
return err
}
return nil
}
// Gets session back from the store. Decrypt the values object back to fit the session object's values field
func (s *MongoStore) Get(sid string) (*sessions.Session, error) {
obj_id, err := primitive.ObjectIDFromHex(sid)
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*s.timeout)
defer cancel()
var sess_ map[string]interface{}
if err := s.Collection.FindOne(ctx, bson.M{
"_id": obj_id,
}).Decode(&sess_); err != nil {
return nil, err
}
sess := new(sessions.Session)
{
sess.ID = sid
sess.Opts = new(sessions.Config)
}
opts, ok := sess_["options"].(string)
if !ok {
return nil, errors.New("invalid options")
}
if err := json.Unmarshal([]byte(opts), sess.Opts); err != nil {
return nil, err
}
vals, ok := sess_["values"].(string)
if !ok {
return nil, errors.New("invalid values")
}
vals, err = s.crypt.Decrypt(vals)
if err != nil {
return nil, err
}
if err := json.Unmarshal([]byte(vals), &sess.Values); err != nil {
return nil, err
}
return sess, nil
}
// Purges the session: TODO; lurky xd
func (s *MongoStore) Purge(sid string) error {
return nil
}