Skip to content

Commit ec7fea0

Browse files
committed
wip(api): disable mongodb dependencies
1 parent 3e6f7ea commit ec7fea0

File tree

17 files changed

+73
-2216
lines changed

17 files changed

+73
-2216
lines changed

api/server.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,17 @@ type env struct {
2222
// MongoURI specifies the connection string for MongoDB.
2323
MongoURI string `env:"MONGO_URI,default=mongodb://mongo:27017/main"`
2424

25+
// PostgresHost specifies the host for PostgreSQL.
26+
PostgresHost string `env:"POSTGRES_HOST,default=postgres"`
27+
// PostgresPort specifies the port for PostgreSQL.
28+
PostgresPort string `env:"POSTGRES_PORT,default=5432"`
29+
// PostgresUser specifies the username for authenticate PostgreSQL.
30+
PostgresUser string `env:"POSTGRES_USER,default=admin"`
31+
// PostgresUser specifies the password for authenticate PostgreSQL.
32+
PostgresPassword string `env:"POSTGRES_PASSWORD,default=admin"`
33+
// PostgresDB especifica o nome do banco de dados PostgreSQL a ser utilizado.
34+
PostgresDB string `env:"POSTGRES_DB,default=main"`
35+
2536
// RedisURI specifies the connection string for Redis.
2637
RedisURI string `env:"REDIS_URI,default=redis://redis:6379"`
2738
// RedisCachePoolSize defines the maximum number of concurrent connections to Redis cache.

api/services/auth.go

Lines changed: 1 addition & 115 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,10 @@ import (
1010
"encoding/base64"
1111
"encoding/hex"
1212
"encoding/pem"
13-
"net"
1413
"slices"
1514
"strings"
1615
"time"
1716

18-
"github.com/cnf/structhash"
1917
"github.com/shellhub-io/shellhub/pkg/api/authorizer"
2018
"github.com/shellhub-io/shellhub/pkg/api/jwttoken"
2119
"github.com/shellhub-io/shellhub/pkg/api/requests"
@@ -66,119 +64,7 @@ type AuthService interface {
6664
}
6765

6866
func (s *service) AuthDevice(ctx context.Context, req requests.DeviceAuth, remoteAddr string) (*models.DeviceAuthResponse, error) {
69-
var identity *models.DeviceIdentity
70-
if req.Identity != nil {
71-
identity = &models.DeviceIdentity{
72-
MAC: req.Identity.MAC,
73-
}
74-
}
75-
76-
var hostname string
77-
if req.Hostname != "" {
78-
hostname = req.Hostname
79-
}
80-
81-
if hostname == "" && (identity == nil || identity.MAC == "") {
82-
return nil, NewErrAuthDeviceNoIdentityAndHostname()
83-
}
84-
85-
auth := models.DeviceAuth{
86-
Hostname: hostname,
87-
Identity: identity,
88-
PublicKey: req.PublicKey,
89-
TenantID: req.TenantID,
90-
}
91-
92-
uid := sha256.Sum256(structhash.Dump(auth, 1))
93-
key := hex.EncodeToString(uid[:])
94-
95-
claims := authorizer.DeviceClaims{
96-
UID: key,
97-
TenantID: req.TenantID,
98-
}
99-
100-
token, err := jwttoken.EncodeDeviceClaims(claims, s.privKey)
101-
if err != nil {
102-
return nil, NewErrTokenSigned(err)
103-
}
104-
105-
type Device struct {
106-
Name string
107-
Namespace string
108-
}
109-
110-
var value *Device
111-
112-
if err := s.cache.Get(ctx, strings.Join([]string{"auth_device", key}, "/"), &value); err == nil && value != nil {
113-
return &models.DeviceAuthResponse{
114-
UID: key,
115-
Token: token,
116-
Name: value.Name,
117-
Namespace: value.Namespace,
118-
}, nil
119-
}
120-
var info *models.DeviceInfo
121-
if req.Info != nil {
122-
info = &models.DeviceInfo{
123-
ID: req.Info.ID,
124-
PrettyName: req.Info.PrettyName,
125-
Version: req.Info.Version,
126-
Arch: req.Info.Arch,
127-
Platform: req.Info.Platform,
128-
}
129-
}
130-
131-
position, err := s.locator.GetPosition(net.ParseIP(remoteAddr))
132-
if err != nil {
133-
return nil, err
134-
}
135-
136-
device := models.Device{
137-
UID: key,
138-
Identity: identity,
139-
Info: info,
140-
PublicKey: req.PublicKey,
141-
TenantID: req.TenantID,
142-
LastSeen: clock.Now(),
143-
RemoteAddr: remoteAddr,
144-
Position: &models.DevicePosition{
145-
Longitude: position.Longitude,
146-
Latitude: position.Latitude,
147-
},
148-
}
149-
150-
// The order here is critical as we don't want to register devices if the tenant id is invalid
151-
namespace, err := s.store.NamespaceGet(ctx, device.TenantID)
152-
if err != nil {
153-
return nil, NewErrNamespaceNotFound(device.TenantID, err)
154-
}
155-
156-
hostname = strings.ToLower(hostname)
157-
158-
if err := s.store.DeviceCreate(ctx, device, hostname); err != nil {
159-
return nil, NewErrDeviceCreate(device, err)
160-
}
161-
162-
for _, uid := range req.Sessions {
163-
if err := s.store.SessionSetLastSeen(ctx, models.UID(uid)); err != nil {
164-
continue
165-
}
166-
}
167-
168-
dev, err := s.store.DeviceGetByUID(ctx, models.UID(device.UID), device.TenantID)
169-
if err != nil {
170-
return nil, NewErrDeviceNotFound(models.UID(device.UID), err)
171-
}
172-
if err := s.cache.Set(ctx, strings.Join([]string{"auth_device", key}, "/"), &Device{Name: dev.Name, Namespace: namespace.Name}, time.Second*30); err != nil {
173-
return nil, err
174-
}
175-
176-
return &models.DeviceAuthResponse{
177-
UID: key,
178-
Token: token,
179-
Name: dev.Name,
180-
Namespace: namespace.Name,
181-
}, nil
67+
return nil, nil
18268
}
18369

18470
func (s *service) AuthLocalUser(ctx context.Context, req *requests.AuthLocalUser, sourceIP string) (*models.UserAuthResponse, int64, string, error) {

api/services/task.go

Lines changed: 0 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,9 @@
11
package services
22

33
import (
4-
"bufio"
5-
"bytes"
64
"context"
7-
"strconv"
8-
"strings"
9-
"time"
105

11-
"github.com/shellhub-io/shellhub/pkg/models"
126
"github.com/shellhub-io/shellhub/pkg/worker"
13-
log "github.com/sirupsen/logrus"
147
)
158

169
const (
@@ -20,59 +13,6 @@ const (
2013
// Device Heartbeat sets the device status to "online". It processes in batch.
2114
func (s *service) DevicesHeartbeat() worker.TaskHandler {
2215
return func(ctx context.Context, payload []byte) error {
23-
log.WithField("task", TaskDevicesHeartbeat.String()).
24-
Info("executing heartbeat task")
25-
26-
scanner := bufio.NewScanner(bytes.NewReader(payload))
27-
scanner.Split(bufio.ScanLines)
28-
29-
devices := make([]models.ConnectedDevice, 0)
30-
for scanner.Scan() {
31-
parts := strings.Split(scanner.Text(), "=")
32-
if len(parts) != 2 {
33-
log.WithField("task", TaskDevicesHeartbeat.String()).
34-
Warn("failed to parse queue payload due to lack of '='.")
35-
36-
continue
37-
}
38-
39-
lastSeen, err := strconv.ParseInt(parts[1], 10, 64)
40-
if err != nil {
41-
log.WithField("task", TaskDevicesHeartbeat.String()).
42-
WithError(err).
43-
Warn("failed to parse timestamp to integer.")
44-
45-
continue
46-
}
47-
48-
parts = strings.Split(parts[0], ":")
49-
if len(parts) != 2 {
50-
log.WithField("task", TaskDevicesHeartbeat.String()).
51-
Warn("failed to parse queue payload due to lack of ':'.")
52-
53-
continue
54-
}
55-
56-
device := models.ConnectedDevice{
57-
UID: parts[1],
58-
TenantID: parts[0],
59-
LastSeen: time.Unix(lastSeen, 0),
60-
}
61-
62-
devices = append(devices, device)
63-
}
64-
65-
if err := s.store.DeviceSetOnline(ctx, devices); err != nil {
66-
log.WithField("task", TaskDevicesHeartbeat.String()).
67-
WithError(err).
68-
Error("failed to complete the heartbeat task")
69-
70-
return err
71-
}
72-
73-
log.WithField("task", TaskDevicesHeartbeat.String()).
74-
Info("finishing heartbeat task")
75-
7616
return nil
7717
}
7818
}

api/store/mongo/api-key.go

Lines changed: 5 additions & 123 deletions
Original file line numberDiff line numberDiff line change
@@ -3,152 +3,34 @@ package mongo
33
import (
44
"context"
55

6-
"github.com/shellhub-io/shellhub/api/store"
7-
"github.com/shellhub-io/shellhub/api/store/mongo/queries"
86
"github.com/shellhub-io/shellhub/pkg/api/query"
9-
"github.com/shellhub-io/shellhub/pkg/clock"
107
"github.com/shellhub-io/shellhub/pkg/models"
11-
"go.mongodb.org/mongo-driver/bson"
128
)
139

1410
func (s *Store) APIKeyCreate(ctx context.Context, apiKey *models.APIKey) (string, error) {
15-
now := clock.Now()
16-
apiKey.CreatedAt = now
17-
apiKey.UpdatedAt = now
18-
19-
res, err := s.db.Collection("api_keys").InsertOne(ctx, apiKey)
20-
if err != nil {
21-
return "", FromMongoError(err)
22-
}
23-
24-
return res.InsertedID.(string), nil
11+
return "", nil
2512
}
2613

2714
func (s *Store) APIKeyGet(ctx context.Context, id string) (*models.APIKey, error) {
28-
apiKey := new(models.APIKey)
29-
if err := s.db.Collection("api_keys").FindOne(ctx, bson.M{"_id": id}).Decode(apiKey); err != nil {
30-
return nil, FromMongoError(err)
31-
}
32-
33-
return apiKey, nil
15+
return nil, nil
3416
}
3517

3618
func (s *Store) APIKeyGetByName(ctx context.Context, tenantID string, name string) (*models.APIKey, error) {
37-
apiKey := new(models.APIKey)
38-
if err := s.db.Collection("api_keys").FindOne(ctx, bson.M{"tenant_id": tenantID, "name": name}).Decode(&apiKey); err != nil {
39-
return nil, FromMongoError(err)
40-
}
41-
42-
return apiKey, nil
19+
return nil, nil
4320
}
4421

4522
func (s *Store) APIKeyConflicts(ctx context.Context, tenantID string, target *models.APIKeyConflicts) ([]string, bool, error) {
46-
pipeline := []bson.M{
47-
{
48-
"$match": bson.M{
49-
"tenant_id": tenantID,
50-
"$or": []bson.M{
51-
{"_id": target.ID},
52-
{"name": target.Name},
53-
},
54-
},
55-
},
56-
}
57-
58-
cursor, err := s.db.Collection("api_keys").Aggregate(ctx, pipeline)
59-
if err != nil {
60-
return nil, false, FromMongoError(err)
61-
}
62-
defer cursor.Close(ctx)
63-
64-
apiKey := new(models.APIKeyConflicts)
65-
conflicts := make([]string, 0)
66-
for cursor.Next(ctx) {
67-
if err := cursor.Decode(&apiKey); err != nil {
68-
return nil, false, FromMongoError(err)
69-
}
70-
71-
if apiKey.ID == target.ID {
72-
conflicts = append(conflicts, "id")
73-
}
74-
75-
if apiKey.Name == target.Name {
76-
conflicts = append(conflicts, "name")
77-
}
78-
}
79-
80-
return conflicts, len(conflicts) > 0, nil
23+
return nil, false, nil
8124
}
8225

8326
func (s *Store) APIKeyList(ctx context.Context, tenantID string, paginator query.Paginator, sorter query.Sorter) ([]models.APIKey, int, error) {
84-
query := []bson.M{
85-
{
86-
"$match": bson.M{
87-
"tenant_id": tenantID,
88-
},
89-
},
90-
}
91-
92-
queryCount := append(query, bson.M{"$count": "count"})
93-
count, err := AggregateCount(ctx, s.db.Collection("api_keys"), queryCount)
94-
if err != nil {
95-
return nil, 0, FromMongoError(err)
96-
}
97-
98-
if count == 0 {
99-
return []models.APIKey{}, 0, nil
100-
}
101-
102-
query = append(query, queries.FromSorter(&sorter)...)
103-
query = append(query, queries.FromPaginator(&paginator)...)
104-
105-
cursor, err := s.db.Collection("api_keys").Aggregate(ctx, query)
106-
if err != nil {
107-
return nil, 0, FromMongoError(err)
108-
}
109-
defer cursor.Close(ctx)
110-
111-
apiKeys := make([]models.APIKey, 0)
112-
for cursor.Next(ctx) {
113-
apiKey := new(models.APIKey)
114-
if err := cursor.Decode(apiKey); err != nil {
115-
return nil, 0, FromMongoError(err)
116-
}
117-
118-
apiKeys = append(apiKeys, *apiKey)
119-
}
120-
121-
return apiKeys, count, nil
27+
return nil, 0, nil
12228
}
12329

12430
func (s *Store) APIKeyUpdate(ctx context.Context, tenantID, name string, changes *models.APIKeyChanges) error {
125-
changes.UpdatedAt = clock.Now()
126-
127-
res, err := s.db.
128-
Collection("api_keys").
129-
UpdateOne(ctx, bson.M{"tenant_id": tenantID, "name": name}, bson.M{"$set": changes})
130-
if err != nil {
131-
return FromMongoError(err)
132-
}
133-
134-
if res.ModifiedCount < 1 {
135-
return store.ErrNoDocuments
136-
}
137-
13831
return nil
13932
}
14033

14134
func (s *Store) APIKeyDelete(ctx context.Context, tenantID, name string) error {
142-
result, err := s.db.
143-
Collection("api_keys").
144-
DeleteOne(ctx, bson.M{"tenant_id": tenantID, "name": name})
145-
if err != nil {
146-
return FromMongoError(err)
147-
}
148-
149-
if result.DeletedCount < 1 {
150-
return store.ErrNoDocuments
151-
}
152-
15335
return nil
15436
}

0 commit comments

Comments
 (0)