-
Notifications
You must be signed in to change notification settings - Fork 63
/
analytics_auth.go
261 lines (210 loc) · 6.97 KB
/
analytics_auth.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
package models
import (
"context"
"database/sql"
"errors"
"fmt"
"github.com/go-jose/go-jose/v4"
"github.com/go-jose/go-jose/v4/jwt"
"github.com/gofiber/fiber/v2"
"github.com/mynaparrot/plugnmeet-protocol/plugnmeet"
"github.com/mynaparrot/plugnmeet-server/pkg/config"
"os"
"strings"
"time"
)
type AnalyticsAuthModel struct {
app *config.AppConfig
db *sql.DB
ctx context.Context
}
func NewAnalyticsAuthModel() *AnalyticsAuthModel {
return &AnalyticsAuthModel{
app: config.AppCnf,
db: config.AppCnf.DB,
ctx: context.Background(),
}
}
func (m *AnalyticsAuthModel) FetchAnalytics(r *plugnmeet.FetchAnalyticsReq) (*plugnmeet.FetchAnalyticsResult, error) {
db := m.db
ctx, cancel := context.WithTimeout(m.ctx, 3*time.Second)
defer cancel()
limit := r.Limit
orderBy := "DESC"
if limit == 0 {
limit = 20
}
if r.OrderBy == "ASC" {
orderBy = "ASC"
}
var rows *sql.Rows
var err error
switch {
case len(r.RoomIds) > 0:
var args []interface{}
for _, rd := range r.RoomIds {
args = append(args, rd)
}
args = append(args, r.From)
args = append(args, limit)
query := "SELECT room_id, file_id, file_name, file_size, room_creation_time, creation_time FROM " + m.app.FormatDBTable("room_analytics") + " WHERE room_id IN (?" + strings.Repeat(",?", len(r.RoomIds)-1) + ") ORDER BY id " + orderBy + " LIMIT ?,?"
rows, err = db.QueryContext(ctx, query, args...)
default:
rows, err = db.QueryContext(ctx, "SELECT room_id, file_id, file_name, file_size, room_creation_time, creation_time FROM "+m.app.FormatDBTable("room_analytics")+" ORDER BY id "+orderBy+" LIMIT ?,?", r.From, limit)
}
if err != nil {
return nil, err
}
defer rows.Close()
var analytics []*plugnmeet.AnalyticsInfo
for rows.Next() {
var analytic plugnmeet.AnalyticsInfo
err = rows.Scan(&analytic.RoomId, &analytic.FileId, &analytic.FileName, &analytic.FileSize, &analytic.RoomCreationTime, &analytic.CreationTime)
if err != nil {
fmt.Println(err)
}
analytics = append(analytics, &analytic)
}
// get total number of analytics
var row *sql.Row
switch {
case len(r.RoomIds) > 0:
var args []interface{}
for _, rd := range r.RoomIds {
args = append(args, rd)
}
query := "SELECT COUNT(*) AS total FROM " + m.app.FormatDBTable("room_analytics") + " WHERE room_id IN (?" + strings.Repeat(",?", len(r.RoomIds)-1) + ")"
row = db.QueryRowContext(ctx, query, args...)
default:
row = db.QueryRowContext(ctx, "SELECT COUNT(*) AS total FROM "+m.app.FormatDBTable("room_analytics"))
}
var total int64
_ = row.Scan(&total)
result := &plugnmeet.FetchAnalyticsResult{
TotalAnalytics: total,
From: r.From,
Limit: limit,
OrderBy: orderBy,
AnalyticsList: analytics,
}
return result, nil
}
func (m *AnalyticsAuthModel) fetchAnalytic(fileId string) (*plugnmeet.AnalyticsInfo, error) {
db := m.db
ctx, cancel := context.WithTimeout(m.ctx, 3*time.Second)
defer cancel()
row := db.QueryRowContext(ctx, "SELECT room_id, file_id, file_name, file_size, room_creation_time, creation_time FROM "+m.app.FormatDBTable("room_analytics")+" WHERE file_id = ?", fileId)
analytic := new(plugnmeet.AnalyticsInfo)
err := row.Scan(&analytic.RoomId, &analytic.FileId, &analytic.FileName, &analytic.FileSize, &analytic.RoomCreationTime, &analytic.CreationTime)
switch {
case errors.Is(err, sql.ErrNoRows):
err = errors.New("no info found")
case err != nil:
err = errors.New(fmt.Sprintf("query error: %s", err.Error()))
}
if err != nil {
return nil, err
}
return analytic, nil
}
func (m *AnalyticsAuthModel) getAnalyticByRoomTableId(roomTableId int64) (*plugnmeet.AnalyticsInfo, error) {
db := m.db
ctx, cancel := context.WithTimeout(m.ctx, 3*time.Second)
defer cancel()
row := db.QueryRowContext(ctx, "SELECT room_id, file_id, file_name, file_size, room_creation_time, creation_time FROM "+m.app.FormatDBTable("room_analytics")+" WHERE room_table_id = ?", roomTableId)
analytic := new(plugnmeet.AnalyticsInfo)
err := row.Scan(&analytic.RoomId, &analytic.FileId, &analytic.FileName, &analytic.FileSize, &analytic.RoomCreationTime, &analytic.CreationTime)
switch {
case errors.Is(err, sql.ErrNoRows):
err = errors.New("no info found")
case err != nil:
err = errors.New(fmt.Sprintf("query error: %s", err.Error()))
}
if err != nil {
return nil, err
}
return analytic, nil
}
func (m *AnalyticsAuthModel) DeleteAnalytics(r *plugnmeet.DeleteAnalyticsReq) error {
analytic, err := m.fetchAnalytic(r.FileId)
if err != nil {
return err
}
path := fmt.Sprintf("%s/%s", *config.AppCnf.AnalyticsSettings.FilesStorePath, analytic.FileName)
// delete main file
err = os.Remove(path)
if err != nil {
// if file not exist then we can delete it from record without showing any error
if !os.IsNotExist(err) {
ms := strings.SplitN(err.Error(), "/", -1)
return errors.New(ms[len(ms)-1])
}
}
// delete compressed, if any
_ = os.Remove(path + ".fiber.gz")
// no error, so we'll delete record from DB
db := m.db
ctx, cancel := context.WithTimeout(m.ctx, 3*time.Second)
defer cancel()
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
stmt, err := tx.Prepare("DELETE FROM " + m.app.FormatDBTable("room_analytics") + " WHERE file_id = ?")
if err != nil {
return err
}
_, err = stmt.Exec(r.FileId)
if err != nil {
return err
}
err = tx.Commit()
if err != nil {
return err
}
err = stmt.Close()
if err != nil {
return err
}
return nil
}
// GetAnalyticsDownloadToken will use the same JWT token generator as plugNmeet is using
func (m *AnalyticsAuthModel) GetAnalyticsDownloadToken(r *plugnmeet.GetAnalyticsDownloadTokenReq) (string, error) {
analytic, err := m.fetchAnalytic(r.FileId)
if err != nil {
return "", err
}
sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.HS256, Key: []byte(m.app.Client.Secret)}, (&jose.SignerOptions{}).WithType("JWT"))
if err != nil {
return "", err
}
cl := jwt.Claims{
Issuer: m.app.Client.ApiKey,
NotBefore: jwt.NewNumericDate(time.Now().UTC()),
Expiry: jwt.NewNumericDate(time.Now().UTC().Add(*m.app.AnalyticsSettings.TokenValidity)),
Subject: analytic.FileName,
}
return jwt.Signed(sig).Claims(cl).Serialize()
}
// VerifyAnalyticsToken verify token & provide file path
func (m *AnalyticsAuthModel) VerifyAnalyticsToken(token string) (string, int, error) {
tok, err := jwt.ParseSigned(token, []jose.SignatureAlgorithm{jose.HS256})
if err != nil {
return "", fiber.StatusUnauthorized, err
}
out := jwt.Claims{}
if err = tok.Claims([]byte(config.AppCnf.Client.Secret), &out); err != nil {
return "", fiber.StatusUnauthorized, err
}
if err = out.Validate(jwt.Expected{Issuer: config.AppCnf.Client.ApiKey, Time: time.Now().UTC()}); err != nil {
return "", fiber.StatusUnauthorized, err
}
file := fmt.Sprintf("%s/%s", *config.AppCnf.AnalyticsSettings.FilesStorePath, out.Subject)
_, err = os.Lstat(file)
if err != nil {
ms := strings.SplitN(err.Error(), "/", -1)
return "", fiber.StatusNotFound, errors.New(ms[len(ms)-1])
}
return file, fiber.StatusOK, nil
}