forked from techschool/simplebank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrpc_update_user.go
100 lines (84 loc) · 2.51 KB
/
rpc_update_user.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
package gapi
import (
"context"
"errors"
"time"
"github.com/jackc/pgx/v5/pgtype"
db "github.com/techschool/simplebank/db/sqlc"
"github.com/techschool/simplebank/pb"
"github.com/techschool/simplebank/util"
"github.com/techschool/simplebank/val"
"google.golang.org/genproto/googleapis/rpc/errdetails"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func (server *Server) UpdateUser(ctx context.Context, req *pb.UpdateUserRequest) (*pb.UpdateUserResponse, error) {
authPayload, err := server.authorizeUser(ctx)
if err != nil {
return nil, unauthenticatedError(err)
}
violations := validateUpdateUserRequest(req)
if violations != nil {
return nil, invalidArgumentError(violations)
}
if authPayload.Username != req.GetUsername() {
return nil, status.Errorf(codes.PermissionDenied, "cannot update other user's info")
}
arg := db.UpdateUserParams{
Username: req.GetUsername(),
FullName: pgtype.Text{
String: req.GetFullName(),
Valid: req.FullName != nil,
},
Email: pgtype.Text{
String: req.GetEmail(),
Valid: req.Email != nil,
},
}
if req.Password != nil {
hashedPassword, err := util.HashPassword(req.GetPassword())
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to hash password: %s", err)
}
arg.HashedPassword = pgtype.Text{
String: hashedPassword,
Valid: true,
}
arg.PasswordChangedAt = pgtype.Timestamptz{
Time: time.Now(),
Valid: true,
}
}
user, err := server.store.UpdateUser(ctx, arg)
if err != nil {
if errors.Is(err, db.ErrRecordNotFound) {
return nil, status.Errorf(codes.NotFound, "user not found")
}
return nil, status.Errorf(codes.Internal, "failed to update user: %s", err)
}
rsp := &pb.UpdateUserResponse{
User: convertUser(user),
}
return rsp, nil
}
func validateUpdateUserRequest(req *pb.UpdateUserRequest) (violations []*errdetails.BadRequest_FieldViolation) {
if err := val.ValidateUsername(req.GetUsername()); err != nil {
violations = append(violations, fieldViolation("username", err))
}
if req.Password != nil {
if err := val.ValidatePassword(req.GetPassword()); err != nil {
violations = append(violations, fieldViolation("password", err))
}
}
if req.FullName != nil {
if err := val.ValidateFullName(req.GetFullName()); err != nil {
violations = append(violations, fieldViolation("full_name", err))
}
}
if req.Email != nil {
if err := val.ValidateEmail(req.GetEmail()); err != nil {
violations = append(violations, fieldViolation("email", err))
}
}
return violations
}