-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpc_list_user_accounts.go
68 lines (58 loc) · 1.9 KB
/
rpc_list_user_accounts.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
package gapi
import (
"context"
"errors"
db "github.com/aradwann/eenergy/db/store"
"github.com/aradwann/eenergy/pb"
"github.com/aradwann/eenergy/util"
"github.com/aradwann/eenergy/val"
"google.golang.org/genproto/googleapis/rpc/errdetails"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func (server *Server) ListUserAccounts(ctx context.Context, req *pb.ListUserAccountsRequest) (*pb.ListUserAccountsResponse, error) {
authPayload, err := server.authorizeUser(ctx, []string{util.AdminRole, util.UserRole})
if err != nil {
return nil, unauthenticatedError(err)
}
violations := validateListUserAccountsRequest(req)
if violations != nil {
return nil, invalidArgumentError(violations)
}
owner := ""
if authPayload.Role == util.UserRole {
owner = authPayload.Username
} else if authPayload.Role == util.AdminRole {
owner = req.GetUsername()
}
arg := db.ListAccountsParams{
Owner: owner,
Limit: req.GetLimit(),
Offset: req.GetOffset(),
}
accs, err := server.store.ListAccounts(ctx, arg)
if err != nil {
if errors.Is(err, db.ErrRecordNotFound) {
return nil, status.Errorf(codes.NotFound, "acc not found")
}
return nil, status.Errorf(codes.Internal, "failed to get user accounts: %s", err)
}
rsp := &pb.ListUserAccountsResponse{
Accounts: convertAccounts(accs),
}
return rsp, nil
}
func validateListUserAccountsRequest(req *pb.ListUserAccountsRequest) (violations []*errdetails.BadRequest_FieldViolation) {
if req.GetUsername() != "" {
if err := val.ValidateUsername(req.GetUsername()); err != nil {
violations = append(violations, fieldViolation("username", err))
}
}
if err := val.ValidateIntNotNegative(int64(req.GetLimit())); err != nil {
violations = append(violations, fieldViolation("limit", err))
}
if err := val.ValidateIntNotNegative(int64(req.GetOffset())); err != nil {
violations = append(violations, fieldViolation("offset", err))
}
return
}