mysqladm/cli/
user_command.rs

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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
use anyhow::Context;
use clap::Parser;
use dialoguer::{Confirm, Password};
use futures_util::{SinkExt, StreamExt};

use crate::core::protocol::{
    print_create_users_output_status, print_create_users_output_status_json,
    print_drop_users_output_status, print_drop_users_output_status_json,
    print_lock_users_output_status, print_lock_users_output_status_json,
    print_set_password_output_status, print_unlock_users_output_status,
    print_unlock_users_output_status_json, ClientToServerMessageStream, ListUsersError, MySQLUser,
    Request, Response,
};

use super::common::erroneous_server_response;

#[derive(Parser, Debug, Clone)]
pub struct UserArgs {
    #[clap(subcommand)]
    subcmd: UserCommand,
}

#[allow(clippy::enum_variant_names)]
#[derive(Parser, Debug, Clone)]
pub enum UserCommand {
    /// Create one or more users
    #[command()]
    CreateUser(UserCreateArgs),

    /// Delete one or more users
    #[command()]
    DropUser(UserDeleteArgs),

    /// Change the MySQL password for a user
    #[command()]
    PasswdUser(UserPasswdArgs),

    /// Print information about one or more users
    ///
    /// If no username is provided, all users you have access will be shown.
    #[command()]
    ShowUser(UserShowArgs),

    /// Lock account for one or more users
    #[command()]
    LockUser(UserLockArgs),

    /// Unlock account for one or more users
    #[command()]
    UnlockUser(UserUnlockArgs),
}

#[derive(Parser, Debug, Clone)]
pub struct UserCreateArgs {
    #[arg(num_args = 1..)]
    username: Vec<MySQLUser>,

    /// Do not ask for a password, leave it unset
    #[clap(long)]
    no_password: bool,

    /// Print the information as JSON
    ///
    /// Note that this implies `--no-password`, since the command will become non-interactive.
    #[arg(short, long)]
    json: bool,
}

#[derive(Parser, Debug, Clone)]
pub struct UserDeleteArgs {
    #[arg(num_args = 1..)]
    username: Vec<MySQLUser>,

    /// Print the information as JSON
    #[arg(short, long)]
    json: bool,
}

#[derive(Parser, Debug, Clone)]
pub struct UserPasswdArgs {
    username: MySQLUser,

    #[clap(short, long)]
    password_file: Option<String>,

    /// Print the information as JSON
    #[arg(short, long)]
    json: bool,
}

#[derive(Parser, Debug, Clone)]
pub struct UserShowArgs {
    #[arg(num_args = 0..)]
    username: Vec<MySQLUser>,

    /// Print the information as JSON
    #[arg(short, long)]
    json: bool,
}

#[derive(Parser, Debug, Clone)]
pub struct UserLockArgs {
    #[arg(num_args = 1..)]
    username: Vec<MySQLUser>,

    /// Print the information as JSON
    #[arg(short, long)]
    json: bool,
}

#[derive(Parser, Debug, Clone)]
pub struct UserUnlockArgs {
    #[arg(num_args = 1..)]
    username: Vec<MySQLUser>,

    /// Print the information as JSON
    #[arg(short, long)]
    json: bool,
}

pub async fn handle_command(
    command: UserCommand,
    server_connection: ClientToServerMessageStream,
) -> anyhow::Result<()> {
    match command {
        UserCommand::CreateUser(args) => create_users(args, server_connection).await,
        UserCommand::DropUser(args) => drop_users(args, server_connection).await,
        UserCommand::PasswdUser(args) => passwd_user(args, server_connection).await,
        UserCommand::ShowUser(args) => show_users(args, server_connection).await,
        UserCommand::LockUser(args) => lock_users(args, server_connection).await,
        UserCommand::UnlockUser(args) => unlock_users(args, server_connection).await,
    }
}

async fn create_users(
    args: UserCreateArgs,
    mut server_connection: ClientToServerMessageStream,
) -> anyhow::Result<()> {
    if args.username.is_empty() {
        anyhow::bail!("No usernames provided");
    }

    let message = Request::CreateUsers(args.username.to_owned());
    if let Err(err) = server_connection.send(message).await {
        server_connection.close().await.ok();
        anyhow::bail!(anyhow::Error::from(err).context("Failed to communicate with server"));
    }

    let result = match server_connection.next().await {
        Some(Ok(Response::CreateUsers(result))) => result,
        response => return erroneous_server_response(response),
    };

    if args.json {
        print_create_users_output_status_json(&result);
    } else {
        print_create_users_output_status(&result);

        let successfully_created_users = result
            .iter()
            .filter_map(|(username, result)| result.as_ref().ok().map(|_| username))
            .collect::<Vec<_>>();

        for username in successfully_created_users {
            if !args.no_password
                && Confirm::new()
                    .with_prompt(format!(
                        "Do you want to set a password for user '{}'?",
                        username
                    ))
                    .default(false)
                    .interact()?
            {
                let password = read_password_from_stdin_with_double_check(username)?;
                let message = Request::PasswdUser(username.to_owned(), password);

                if let Err(err) = server_connection.send(message).await {
                    server_connection.close().await.ok();
                    anyhow::bail!(err);
                }

                match server_connection.next().await {
                    Some(Ok(Response::PasswdUser(result))) => {
                        print_set_password_output_status(&result, username)
                    }
                    response => return erroneous_server_response(response),
                }

                println!();
            }
        }
    }

    server_connection.send(Request::Exit).await?;

    Ok(())
}

async fn drop_users(
    args: UserDeleteArgs,
    mut server_connection: ClientToServerMessageStream,
) -> anyhow::Result<()> {
    if args.username.is_empty() {
        anyhow::bail!("No usernames provided");
    }

    let message = Request::DropUsers(args.username.to_owned());

    if let Err(err) = server_connection.send(message).await {
        server_connection.close().await.ok();
        anyhow::bail!(err);
    }

    let result = match server_connection.next().await {
        Some(Ok(Response::DropUsers(result))) => result,
        response => return erroneous_server_response(response),
    };

    server_connection.send(Request::Exit).await?;

    if args.json {
        print_drop_users_output_status_json(&result);
    } else {
        print_drop_users_output_status(&result);
    }

    Ok(())
}

pub fn read_password_from_stdin_with_double_check(username: &MySQLUser) -> anyhow::Result<String> {
    Password::new()
        .with_prompt(format!("New MySQL password for user '{}'", username))
        .with_confirmation(
            format!("Retype new MySQL password for user '{}'", username),
            "Passwords do not match",
        )
        .interact()
        .map_err(Into::into)
}

async fn passwd_user(
    args: UserPasswdArgs,
    mut server_connection: ClientToServerMessageStream,
) -> anyhow::Result<()> {
    // TODO: create a "user" exists check" command
    let message = Request::ListUsers(Some(vec![args.username.to_owned()]));
    if let Err(err) = server_connection.send(message).await {
        server_connection.close().await.ok();
        anyhow::bail!(err);
    }
    let response = match server_connection.next().await {
        Some(Ok(Response::ListUsers(users))) => users,
        response => return erroneous_server_response(response),
    };
    match response
        .get(&args.username)
        .unwrap_or(&Err(ListUsersError::UserDoesNotExist))
    {
        Ok(_) => {}
        Err(err) => {
            server_connection.send(Request::Exit).await?;
            server_connection.close().await.ok();
            anyhow::bail!("{}", err.to_error_message(&args.username));
        }
    }

    let password = if let Some(password_file) = args.password_file {
        std::fs::read_to_string(password_file)
            .context("Failed to read password file")?
            .trim()
            .to_string()
    } else {
        read_password_from_stdin_with_double_check(&args.username)?
    };

    let message = Request::PasswdUser(args.username.to_owned(), password);

    if let Err(err) = server_connection.send(message).await {
        server_connection.close().await.ok();
        anyhow::bail!(err);
    }

    let result = match server_connection.next().await {
        Some(Ok(Response::PasswdUser(result))) => result,
        response => return erroneous_server_response(response),
    };

    server_connection.send(Request::Exit).await?;

    print_set_password_output_status(&result, &args.username);

    Ok(())
}

async fn show_users(
    args: UserShowArgs,
    mut server_connection: ClientToServerMessageStream,
) -> anyhow::Result<()> {
    let message = if args.username.is_empty() {
        Request::ListUsers(None)
    } else {
        Request::ListUsers(Some(args.username.to_owned()))
    };

    if let Err(err) = server_connection.send(message).await {
        server_connection.close().await.ok();
        anyhow::bail!(err);
    }

    let users = match server_connection.next().await {
        Some(Ok(Response::ListUsers(users))) => users
            .into_iter()
            .filter_map(|(username, result)| match result {
                Ok(user) => Some(user),
                Err(err) => {
                    eprintln!("{}", err.to_error_message(&username));
                    eprintln!("Skipping...");
                    None
                }
            })
            .collect::<Vec<_>>(),
        Some(Ok(Response::ListAllUsers(users))) => match users {
            Ok(users) => users,
            Err(err) => {
                server_connection.send(Request::Exit).await?;
                return Err(
                    anyhow::anyhow!(err.to_error_message()).context("Failed to list all users")
                );
            }
        },
        response => return erroneous_server_response(response),
    };

    server_connection.send(Request::Exit).await?;

    if args.json {
        println!(
            "{}",
            serde_json::to_string_pretty(&users).context("Failed to serialize users to JSON")?
        );
    } else if users.is_empty() {
        println!("No users to show.");
    } else {
        let mut table = prettytable::Table::new();
        table.add_row(row![
            "User",
            "Password is set",
            "Locked",
            "Databases where user has privileges"
        ]);
        for user in users {
            table.add_row(row![
                user.user,
                user.has_password,
                user.is_locked,
                user.databases.join("\n")
            ]);
        }
        table.printstd();
    }

    Ok(())
}

async fn lock_users(
    args: UserLockArgs,
    mut server_connection: ClientToServerMessageStream,
) -> anyhow::Result<()> {
    if args.username.is_empty() {
        anyhow::bail!("No usernames provided");
    }

    let message = Request::LockUsers(args.username.to_owned());

    if let Err(err) = server_connection.send(message).await {
        server_connection.close().await.ok();
        anyhow::bail!(err);
    }

    let result = match server_connection.next().await {
        Some(Ok(Response::LockUsers(result))) => result,
        response => return erroneous_server_response(response),
    };

    server_connection.send(Request::Exit).await?;

    if args.json {
        print_lock_users_output_status_json(&result);
    } else {
        print_lock_users_output_status(&result);
    }

    Ok(())
}

async fn unlock_users(
    args: UserUnlockArgs,
    mut server_connection: ClientToServerMessageStream,
) -> anyhow::Result<()> {
    if args.username.is_empty() {
        anyhow::bail!("No usernames provided");
    }

    let message = Request::UnlockUsers(args.username.to_owned());

    if let Err(err) = server_connection.send(message).await {
        server_connection.close().await.ok();
        anyhow::bail!(err);
    }

    let result = match server_connection.next().await {
        Some(Ok(Response::UnlockUsers(result))) => result,
        response => return erroneous_server_response(response),
    };

    server_connection.send(Request::Exit).await?;

    if args.json {
        print_unlock_users_output_status_json(&result);
    } else {
        print_unlock_users_output_status(&result);
    }

    Ok(())
}