| 65 | } |
| 66 | |
| 67 | func (c *Client) CreateMachine(ctx context.Context, machineID *string, password *strfmt.Password, ipAddress string, isValidated bool, force bool, authType string) (*ent.Machine, error) { |
| 68 | hashPassword, err := bcrypt.GenerateFromPassword([]byte(*password), bcrypt.DefaultCost) |
| 69 | if err != nil { |
| 70 | c.Log.Warningf("CreateMachine: %s", err) |
| 71 | return nil, HashError |
| 72 | } |
| 73 | |
| 74 | machineExist, err := c.Ent.Machine. |
| 75 | Query(). |
| 76 | Where(machine.MachineIdEQ(*machineID)). |
| 77 | Select(machine.FieldMachineId).Strings(ctx) |
| 78 | if err != nil { |
| 79 | return nil, fmt.Errorf("machine '%s': %w: %w", *machineID, err, QueryFail) |
| 80 | } |
| 81 | |
| 82 | if len(machineExist) > 0 { |
| 83 | if force { |
| 84 | _, err := c.Ent.Machine.Update().Where(machine.MachineIdEQ(*machineID)).SetPassword(string(hashPassword)).Save(ctx) |
| 85 | if err != nil { |
| 86 | c.Log.Warningf("CreateMachine : %s", err) |
| 87 | return nil, fmt.Errorf("machine '%s': %w", *machineID, UpdateFail) |
| 88 | } |
| 89 | |
| 90 | machine, err := c.QueryMachineByID(ctx, *machineID) |
| 91 | if err != nil { |
| 92 | return nil, fmt.Errorf("machine '%s': %w: %w", *machineID, err, QueryFail) |
| 93 | } |
| 94 | |
| 95 | return machine, nil |
| 96 | } |
| 97 | |
| 98 | return nil, fmt.Errorf("user '%s': %w", *machineID, UserExists) |
| 99 | } |
| 100 | |
| 101 | machine, err := c.Ent.Machine. |
| 102 | Create(). |
| 103 | SetMachineId(*machineID). |
| 104 | SetPassword(string(hashPassword)). |
| 105 | SetIpAddress(ipAddress). |
| 106 | SetIsValidated(isValidated). |
| 107 | SetAuthType(authType). |
| 108 | Save(ctx) |
| 109 | if err != nil { |
| 110 | c.Log.Warningf("CreateMachine : %s", err) |
| 111 | return nil, fmt.Errorf("creating machine '%s': %w", *machineID, InsertFail) |
| 112 | } |
| 113 | |
| 114 | return machine, nil |
| 115 | } |
| 116 | |
| 117 | func (c *Client) QueryMachineByID(ctx context.Context, machineID string) (*ent.Machine, error) { |
| 118 | machine, err := c.Ent.Machine. |