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
use crate::error::{Error::AuthenticationError, Result};
use ssh2::Session;
use std::path::PathBuf;

#[derive(Clone, Debug, PartialEq)]
pub enum AuthenticationType {
  Interactive,
  KeyFile(PathBuf),
  Password(String),
}

impl AuthenticationType {
  pub(crate) fn authenticate(&self, session: &Session, username: &str) -> Result<()> {
    if session.authenticated() {
      return Ok(());
    }

    let authentication_methods: Vec<String> = session
      .auth_methods(username)?
      .split(',')
      .map(String::from)
      .collect();

    match &self {
      AuthenticationType::Interactive => {
        unimplemented!()
      }
      AuthenticationType::KeyFile(_key_file_path) => {
        unimplemented!()
      }
      AuthenticationType::Password(password) => {
        if authentication_methods.contains(&"password".to_string()) {
          session.userauth_password(username, password)?;
        }
      }
    }

    if !session.authenticated() {
      return Err(AuthenticationError(format!(
        "Could not authenticate user: {}.",
        username
      )));
    }

    Ok(())
  }
}