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
//! This module contains all the non-admin functions that can be mapped to an
//! endpoint provided by the [CCash](https://github.com/EntireTwix/CCash) API.
//! All admin functions can be found within the [`admin`] module.

pub mod admin;

use crate::{request::request, *};
use reqwest::Method;
use velcro::hash_map;

/// Returns the balance of the [`user`](CCashUser).
pub async fn get_balance(
    session: &CCashSession,
    user: &CCashUser,
) -> Result<u32, CCashError> {
    let url = format!(
        "{}/user/balance?name={}",
        &session.session_url, &user.username
    );

    let r = request::<()>(Method::GET, session, &url, Some(user), None).await?;
    if let Ok(v) = r.convert_message::<u32>() {
        Ok(v)
    } else {
        Err(r.into())
    }
}

/// Returns the transaction logs for a given [`user`](CCashUser). This function
/// requires a correct password.
pub async fn get_logs(
    session: &CCashSession,
    user: &CCashUser,
) -> Result<Vec<TransactionLog>, CCashError> {
    let url = format!("{}/user/log", &session.session_url);

    let r = request::<()>(Method::GET, session, &url, Some(user), None).await?;
    if let Ok(v) = r.convert_message::<Vec<TransactionLog>>() {
        Ok(v)
    } else {
        Err(r.into())
    }
}

/// Returns a `bool` about whether or not the the user with a given
/// [`user`](CCashUser) exists. This function does not require a password.
pub async fn contains_user(
    session: &CCashSession,
    user: &CCashUser,
) -> Result<bool, CCashError> {
    let url = format!(
        "{}/user/exists?name={}",
        &session.session_url, &user.username
    );

    let r = request::<()>(Method::GET, session, &url, Some(user), None).await?;
    match r {
        CCashResponse::Success { .. } => Ok(true),
        #[cfg(feature = "interpret_endpoint_errors_as_false")]
        CCashResponse::Error { .. } => Ok(false),
        #[cfg(not(feature = "interpret_endpoint_errors_as_false"))]
        CCashResponse::Error { code: 401, .. } => Ok(false),
        #[cfg(not(feature = "interpret_endpoint_errors_as_false"))]
        CCashResponse::Error { .. } => Err(r.into()),
    }
}

/// Returns a `bool` about whether or not the `password` for a
/// given [`user`](CCashUser) is correct.
pub async fn verify_password(
    session: &CCashSession,
    user: &CCashUser,
) -> Result<bool, CCashError> {
    let url = format!("{}/user/verify_password", &session.session_url);

    let r = request::<()>(Method::POST, session, &url, Some(user), None).await?;
    match r {
        CCashResponse::Success { .. } => Ok(true),
        #[cfg(feature = "interpret_endpoint_errors_as_false")]
        CCashResponse::Error { .. } => Ok(false),
        #[cfg(not(feature = "interpret_endpoint_errors_as_false"))]
        CCashResponse::Error { code: 401, .. } => Ok(false),
        #[cfg(not(feature = "interpret_endpoint_errors_as_false"))]
        CCashResponse::Error { .. } => Err(r.into()),
    }
}

/// Returns `true` about if a password change was successful for the given
/// [`user`](CCashUser). This function modifies `user` to use the `new_password`
/// instead of the previous password in the case of a successful password
/// change.
pub async fn change_password(
    session: &CCashSession,
    user: &mut CCashUser,
    new_password: &str,
) -> Result<bool, CCashError> {
    let url = format!("{}/user/change_password", &session.session_url);
    let body = hash_map! { "pass": new_password };

    let r = request(Method::PATCH, session, &url, Some(user), Some(&body)).await?;
    match r {
        CCashResponse::Success { .. } => {
            user.update_password(new_password);
            Ok(true)
        },
        #[cfg(feature = "interpret_endpoint_errors_as_false")]
        CCashResponse::Error { .. } => Ok(false),
        #[cfg(not(feature = "interpret_endpoint_errors_as_false"))]
        CCashResponse::Error { .. } => Err(r.into()),
    }
}

/// Sends funds from the [`user`](CCashUser) to the user with the
/// `recipient_name`. This function returns the [`user`](CCashUser)'s balance
/// after a successful transaction has been made.
pub async fn send_funds(
    session: &CCashSession,
    user: &CCashUser,
    recipient_name: &str,
    amount: u32,
) -> Result<u32, CCashError> {
    #[derive(serde::Serialize)]
    struct FundsTransfer {
        name: String,
        amount: u32,
    }

    let url = format!("{}/user/transfer", &session.session_url);
    let body = FundsTransfer {
        name: recipient_name.into(),
        amount,
    };

    let r = request(Method::POST, session, &url, Some(user), Some(&body)).await?;

    if let Ok(v) = r.convert_message::<u32>() {
        Ok(v)
    } else {
        Err(r.into())
    }
}

/// Adds a [`user`](CCashUser) with a balance of 0.
///
/// Returns:
/// * `Ok(true)` if the `user` was created successfully on the CCash instance.
/// * `Ok(false)` if the `user` failed to be created on the CCash instance. This
///   either happens only an a 409 response from the instance or if the feature
///   "interpret_endpoint_errors_as_false" is enabled.
/// * `Error(CCashError)` if the instance returns an error response (other than
///   a 409) *and* the feature "interpret_endpoint_errors_as_false" is disabled.
pub async fn add_user(
    session: &CCashSession,
    user: &CCashUser,
) -> Result<bool, CCashError> {
    let url = format!("{}/user/register", &session.session_url);

    let r = request(Method::POST, session, &url, None, Some(user)).await?;
    match r {
        CCashResponse::Success { .. } => Ok(true),
        #[cfg(feature = "interpret_endpoint_errors_as_false")]
        CCashResponse::Error { .. } => Ok(false),
        #[cfg(not(feature = "interpret_endpoint_errors_as_false"))]
        CCashResponse::Error { code: 409, .. } => Ok(false),
        #[cfg(not(feature = "interpret_endpoint_errors_as_false"))]
        CCashResponse::Error { .. } => Err(r.into()),
    }
}

/// Removes the [`user`](CCashUser). This function requires the
/// [`user`](CCashUser) to be a valid username and password otherwise the
/// endpoint will return an error.
pub async fn delete_user(
    session: &CCashSession,
    user: &CCashUser,
) -> Result<(), CCashError> {
    let url = format!("{}/user/delete", &session.session_url);

    let r = request::<()>(Method::DELETE, session, &url, Some(user), None).await?;
    match r {
        CCashResponse::Success { .. } => Ok(()),
        CCashResponse::Error { .. } => Err(r.into()),
    }
}