-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutilities.go
More file actions
309 lines (289 loc) · 7.92 KB
/
utilities.go
File metadata and controls
309 lines (289 loc) · 7.92 KB
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
package main
import (
"crypto/rand"
"crypto/sha1"
"errors"
"fmt"
mathrand "math/rand"
"net/http"
"sync"
"time"
_ "github.com/lib/pq"
log "github.com/sirupsen/logrus"
)
func Encrypt(plaintext string) (cryptext string, err error) {
if plaintext == "" {
err = errors.New("Empty string")
return
}
cryptext = fmt.Sprintf("%x", sha1.Sum([]byte(plaintext)))
return
}
func CreateUUID() (uuid string, err error) {
u := new([16]byte)
_, err = rand.Read(u[:])
if err != nil {
log.WithFields(log.Fields{
"custom_msg": "Error during UUID creation",
}).Error(err)
err = errors.New("Error creating UUID")
return
}
// 0x40 is reserved variant from RFC 4122
u[8] = (u[8] | 0x40) & 0x7F
// Set the four most significant bits (bits 12 through 15) of the
// time_hi_and_version field to the 4-bit version number.
u[6] = (u[6] & 0xF) | (0x4 << 4)
uuid = fmt.Sprintf("%x-%x-%x-%x-%x", u[0:4], u[4:6], u[6:8], u[8:10], u[10:])
return
}
func RandStringBytes(n int) string {
r := mathrand.New(mathrand.NewSource(time.Now().UnixNano()))
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[r.Intn(len(letterBytes))]
}
return string(b)
}
func (connection *Connection) CheckConnection() {
follow_sql := func(wg *sync.WaitGroup) {
defer wg.Done()
_ = Db.QueryRow(`
SELECT TRUE
FROM followers
WHERE followfrom = $1
AND followto = $2;`, connection.Observer.Wallet, connection.Observed.Wallet).Scan(
&connection.IsFollower,
)
}
subscribe_sql := func(wg *sync.WaitGroup) {
defer wg.Done()
_ = Db.QueryRow(`
SELECT TRUE
FROM subscribers
WHERE subscribefrom = $1
AND subscribeto = $2;`, connection.Observer.Wallet, connection.Observed.Wallet).Scan(
&connection.IsSubscriber,
)
}
var wg sync.WaitGroup
wg.Add(2)
go follow_sql(&wg)
go subscribe_sql(&wg)
wg.Wait()
}
func (connection *Connection) CheckPrivacy() {
if connection.Observed.Privacy == "all" {
connection.Privacy.Status = "OK"
connection.Privacy.Reason = "observed ALL"
return
}
if connection.Observer.Wallet == "" {
connection.Privacy.Status = "KO"
connection.Privacy.Reason = "user is not logged in"
connection.Privacy.Message = "You need to login to visualise these infos!"
return
}
if connection.Observer.Wallet == connection.Observed.Wallet {
connection.Privacy.Status = "OK"
connection.Privacy.Reason = "user access its own profile"
return
}
switch connection.Observed.Privacy {
case "private":
connection.Privacy.Status = "KO"
connection.Privacy.Reason = "private"
connection.Privacy.Message = "This user prefers to keep things private!"
return
case "followers":
if connection.IsFollower {
connection.Privacy.Status = "OK"
connection.Privacy.Reason = "user is follower"
return
} else {
connection.Privacy.Status = "KO"
connection.Privacy.Reason = "user is not follower"
connection.Privacy.Message = "This user shares infos only with followers!"
return
}
case "subscribers":
if connection.IsSubscriber {
connection.Privacy.Status = "OK"
connection.Privacy.Reason = "user is subscriber"
return
} else {
connection.Privacy.Status = "KO"
connection.Privacy.Reason = "user is not subscriber"
connection.Privacy.Message = "This user shares infos only with subscribers!"
return
}
default:
log.WithFields(log.Fields{
"observed": connection.Observer.Wallet,
"observer": connection.Observer.Wallet,
}).Warn("Not possible to determine user's privacy")
connection.Privacy.Status = "KO"
connection.Privacy.Reason = "unknown reason"
return
}
}
func (observed *User) CheckVisibility(snapshot *TradesSnapshot) {
visibility_sql := `
SELECT
totalcounttrades,
totalportfolio,
totalreturn,
totalroi,
tradeqtyavailable,
tradevalue,
tradereturn,
traderoi,
subtradesall,
subtradereasons,
subtradequantity,
subtradeavgprice,
subtradetotal
FROM visibilities
WHERE wallet = $1;`
err := Db.QueryRow(
visibility_sql,
observed.Wallet).Scan(
&snapshot.VisibilityStatus.TotalCountTrades,
&snapshot.VisibilityStatus.TotalPortfolio,
&snapshot.VisibilityStatus.TotalReturn,
&snapshot.VisibilityStatus.TotalRoi,
&snapshot.VisibilityStatus.TradeQtyAvailable,
&snapshot.VisibilityStatus.TradeValue,
&snapshot.VisibilityStatus.TradeReturn,
&snapshot.VisibilityStatus.TradeRoi,
&snapshot.VisibilityStatus.SubtradesAll,
&snapshot.VisibilityStatus.SubtradeReasons,
&snapshot.VisibilityStatus.SubtradeQuantity,
&snapshot.VisibilityStatus.SubtradeAvgPrice,
&snapshot.VisibilityStatus.SubtradeTotal,
)
if err != nil {
log.WithFields(log.Fields{
"wallet": observed.Wallet,
"customMsg": "Failed extracting visibilities",
}).Error(err)
return
}
if !snapshot.VisibilityStatus.TotalCountTrades {
snapshot.CountTrades = 0
}
if !snapshot.VisibilityStatus.TotalPortfolio {
snapshot.TotalPortfolioUsd = "0"
}
if !snapshot.VisibilityStatus.TotalReturn {
snapshot.TotalReturnBtc = "0"
snapshot.TotalReturnUsd = "0"
}
if !snapshot.VisibilityStatus.TotalRoi {
snapshot.Roi = 0
}
if !snapshot.VisibilityStatus.TradeQtyAvailable {
for i := range snapshot.Trades {
snapshot.Trades[i].QtyAvailable = "0"
}
}
if !snapshot.VisibilityStatus.TradeValue {
for i := range snapshot.Trades {
snapshot.Trades[i].TotalValueUsd = 0
snapshot.Trades[i].TotalValueUsdS = "0"
}
}
if !snapshot.VisibilityStatus.TradeReturn {
for i := range snapshot.Trades {
snapshot.Trades[i].TotalReturn = 0
snapshot.Trades[i].TotalReturnUsd = 0
snapshot.Trades[i].TotalReturnBtc = 0
snapshot.Trades[i].TotalReturnS = "0"
}
}
if !snapshot.VisibilityStatus.TradeRoi {
for i := range snapshot.Trades {
snapshot.Trades[i].Roi = 0
}
}
if !snapshot.VisibilityStatus.SubtradesAll {
for i := range snapshot.Trades {
snapshot.Trades[i].Subtrades = []Subtrade{}
}
}
if !snapshot.VisibilityStatus.SubtradeReasons {
for i := range snapshot.Trades {
for q := range snapshot.Trades[i].Subtrades {
snapshot.Trades[i].Subtrades[q].Reason = ""
}
}
}
if !snapshot.VisibilityStatus.SubtradeQuantity {
for i := range snapshot.Trades {
for q := range snapshot.Trades[i].Subtrades {
snapshot.Trades[i].Subtrades[q].Quantity = 0
}
}
}
if !snapshot.VisibilityStatus.SubtradeAvgPrice {
for i := range snapshot.Trades {
for q := range snapshot.Trades[i].Subtrades {
snapshot.Trades[i].Subtrades[q].AvgPrice = 0
}
}
}
if !snapshot.VisibilityStatus.SubtradeTotal {
for i := range snapshot.Trades {
for q := range snapshot.Trades[i].Subtrades {
snapshot.Trades[i].Subtrades[q].Total = 0
}
}
}
}
func GenerateApiToken(w http.ResponseWriter, r *http.Request) {
session, err := GetSession(r, "header")
if err != nil {
log.WithFields(log.Fields{
"customMsg": "Failed generating API token, wrong header",
}).Error(err)
w.WriteHeader(http.StatusUnauthorized)
return
}
if session.Origin != "web" {
log.Error("Failed generating API token, origin not web")
w.WriteHeader(http.StatusBadRequest)
return
}
user, err := SelectUser("wallet", session.UserWallet)
if err != nil {
log.WithFields(log.Fields{
"customMsg": "Failed generating API token, wrong user",
"userWallet": session.UserWallet,
}).Error(err)
w.WriteHeader(http.StatusBadRequest)
return
}
_, err = Db.Exec(`
DELETE FROM sessions
WHERE userwallet = $1 AND origin = 'api';`,
user.Wallet)
if err != nil {
log.WithFields(log.Fields{
"customMsg": "Failed generating API token, cannot delete acutal sessions",
"userWallet": user.Wallet,
}).Error(err)
w.WriteHeader(http.StatusBadRequest)
return
}
apiSession, err := user.InsertSession("api", session.Timezone)
if err != nil {
log.WithFields(log.Fields{
"customMsg": "Failed generating API token, wrong session",
"userWallet": apiSession.UserWallet,
}).Error(err)
w.WriteHeader(http.StatusBadRequest)
return
}
w.Write([]byte(apiSession.Code))
}