Esempio n. 1
0
// RegisterDevice try to register a device to our platform.
// if the device has already been registered,
// the registration will success return the registered device before.
func (r *Registry) RegisterDevice(args *rpcs.ArgsDeviceRegister, reply *models.Device) error {
	db, err := getDB()
	if err != nil {
		return err
	}

	product := &models.Product{}
	err = r.ValidateProduct(args.ProductKey, product)
	if err != nil {
		return err
	}

	identifier := genDeviceIdentifier(product.VendorID, product.ID, args.DeviceCode)
	if db.Where(&models.Device{DeviceIdentifier: identifier}).First(reply).RecordNotFound() {
		// device is not registered yet.
		reply.ProductID = product.ID
		reply.DeviceIdentifier = identifier
		reply.DeviceName = product.ProductName // product name as default device name.
		reply.DeviceDescription = product.ProductDescription
		reply.DeviceVersion = args.DeviceVersion
		err = db.Save(reply).Error
		if err != nil {
			return err
		}
		// generate a random device key with hex encoding.
		reply.DeviceKey, err = r.keygen.GenRandomKey(reply.ID)
		if err != nil {
			return err
		}
		// generate a random password with base64 encoding.
		reply.DeviceSecret, err = generator.GenRandomPassword()
		if err != nil {
			return err
		}

		err = db.Save(reply).Error
		if err != nil {
			return err
		}
	} else {

		//delete cache
		cache := getCache()
		cacheKey := fmt.Sprintf("Device:%v", identifier)
		if _, ok := cache.Get(cacheKey); ok {
			cache.Delete(cacheKey)
		}

		// device has aleady been saved. just update version info.
		reply.DeviceVersion = args.DeviceVersion
		err = db.Save(reply).Error
		if err != nil {
			return err
		}

	}

	return nil
}
Esempio n. 2
0
func setDevice(target *models.Device, src *models.Device) {
	target.ID = src.ID
	target.ProductID = src.ProductID
	target.DeviceIdentifier = src.DeviceIdentifier
	target.DeviceSecret = src.DeviceIdentifier
	target.DeviceKey = src.DeviceKey
	target.DeviceName = src.DeviceName
	target.DeviceDescription = src.DeviceDescription
	target.DeviceVersion = src.DeviceVersion
	target.CreatedAt = src.CreatedAt
	target.UpdatedAt = src.UpdatedAt
}