This repository has been archived by the owner on Jun 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.go
77 lines (64 loc) · 1.69 KB
/
storage.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
package clihelper
import (
"context"
"fmt"
"os"
clipb "github.com/ksusonic/gophkeeper/proto/cli"
grpcMetadata "google.golang.org/grpc/metadata"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/metadata"
"github.com/urfave/cli/v2"
"google.golang.org/protobuf/proto"
)
type Storage struct {
path string
*clipb.Storage
}
func NewStorage(path string, ignoreErrors bool) (*Storage, error) {
storage := &Storage{path: path, Storage: &clipb.Storage{}}
file, _ := os.ReadFile(path)
if file != nil {
err := proto.Unmarshal(file, storage.Storage)
if err != nil {
if ignoreErrors {
return storage, nil
}
return nil, fmt.Errorf("could not unmarshall storage proto: %v", err)
}
return storage, nil
}
return storage, nil
}
func (s *Storage) Save() error {
marshal, err := proto.Marshal(s.Storage)
if err != nil {
return err
}
file, err := os.OpenFile(s.path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
if err != nil {
return fmt.Errorf("could not create temp dir for file: %w", err)
}
defer file.Close()
_, err = file.Write(marshal)
if err != nil {
return err
}
return nil
}
func (s *Storage) TokenIsValidError(_ context.Context) error {
if len(s.Token) == 0 {
return fmt.Errorf("access token is empty")
}
// TODO: validate handler
return nil
}
func (s *Storage) TokenIsValid(ctx context.Context) bool {
return s.TokenIsValidError(ctx) == nil
}
func (s *Storage) LoginInterceptor(ctx *cli.Context) error {
if err := s.TokenIsValidError(ctx.Context); err != nil {
return fmt.Errorf("you need to be logged in: %w", err)
}
md := grpcMetadata.Pairs("authorization", fmt.Sprintf("%s %v", "bearer", s.Token))
ctx.Context = metadata.MD(md).ToOutgoing(ctx.Context)
return nil
}