Skip to content

Commit 6b72a8a

Browse files
henrybarretogustavosbarreto
authored andcommitted
feature(api,pkg): add validation rule to device's name
1 parent 44deb31 commit 6b72a8a

File tree

4 files changed

+14
-2
lines changed

4 files changed

+14
-2
lines changed

api/services/device.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -350,7 +350,8 @@ func (s *service) UpdateDevice(ctx context.Context, tenant string, uid models.UI
350350
return nil
351351
}
352352

353-
if ok := validator.ValidateField(models.Device{}, "Name", *name); !ok {
353+
v := validator.New()
354+
if ok, err := v.Var(*name, "device_name"); err != nil || !ok {
354355
return NewErrDeviceInvalid(map[string]interface{}{"name": *name}, nil)
355356
}
356357

pkg/models/device.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ const (
1919
type Device struct {
2020
// UID is the unique identifier for a device.
2121
UID string `json:"uid"`
22-
Name string `json:"name" bson:"name,omitempty" validate:"required,hostname_rfc1123,excludes=."`
22+
Name string `json:"name" bson:"name,omitempty" validate:"required,device_name"`
2323
Identity *DeviceIdentity `json:"identity"`
2424
Info *DeviceInfo `json:"info"`
2525
PublicKey string `json:"public_key" bson:"public_key"`

pkg/validator/deprecated.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,10 @@ func init() {
3131
return regexp.MustCompile(`^([a-zA-Z0-9-_.@]){3,30}$`).MatchString(fl.Field().String())
3232
})
3333

34+
_ = validate.RegisterValidation("device_name", func(fl validator.FieldLevel) bool {
35+
return regexp.MustCompile(`^([a-zA-Z0-9_-]){1,64}$`).MatchString(fl.Field().String())
36+
})
37+
3438
instance = validate
3539
}
3640

pkg/validator/validator.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,13 @@ var Rules = []Rule{
3939
},
4040
Error: fmt.Errorf("the password cannot be empty and must be between 5 and 30 characters"),
4141
},
42+
{
43+
Tag: "device_name",
44+
Handler: func(field validator.FieldLevel) bool {
45+
return regexp.MustCompile(`^([a-zA-Z0-9_.-] ){1,64}$`).MatchString(field.Field().String())
46+
},
47+
Error: fmt.Errorf("the device name can only contain `_`, `.` and alpha numeric characters"),
48+
},
4249
}
4350

4451
// Validator is the ShellHub validator.

0 commit comments

Comments
 (0)