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

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

/// Returns a boolean whether or not the [`user`](CCashUser) is an admin
/// account.
pub async fn verify_account(
    session: &CCashSession,
    user: &CCashUser,
) -> Result<bool, CCashError> {
    let url = format!("{}/admin/verify_account", &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()),
    }
}

/// Changes the password for the [`user`](CCashUser). This function modifies
/// `user` to use the `new_password` instead of the previous password in the
/// case of a successful password change. This function requires
/// [`admin_user`](CCashUser) to be equal to the admin user of the CCash
/// instance.
pub async fn change_password(
    session: &CCashSession,
    admin_user: &CCashUser,
    user: &mut CCashUser,
    new_password: &str,
) -> Result<bool, CCashError> {
    let url = format!("{}/admin/user/change_password", &session.session_url);

    let new_user = CCashUser {
        username: user.username.clone(),
        password: new_password.into(),
    };

    let r = request(
        Method::PATCH,
        session,
        &url,
        Some(admin_user),
        Some(&new_user),
    )
    .await?;

    match r {
        CCashResponse::Success { .. } => {
            *user = new_user;
            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()),
    }
}

/// Sets the balance of a user with the given `username` to the amount described
/// by `new_balance`. This function requires [`admin_user`](CCashUser) to be the
/// admin account for the CCash instance.
pub async fn set_balance(
    session: &CCashSession,
    admin_user: &CCashUser,
    username: &str,
    new_balance: u32,
) -> Result<(), CCashError> {
    #[derive(serde::Serialize)]
    struct SetBalanceData {
        name: String,
        amount: u32,
    }

    let url = format!("{}/admin/set_balance", &session.session_url);

    let body = SetBalanceData {
        name: username.into(),
        amount: new_balance,
    };

    let r = request(Method::PATCH, session, &url, Some(admin_user), Some(&body)).await?;
    match r {
        CCashResponse::Success { .. } => Ok(()),
        CCashResponse::Error { .. } => Err(r.into()),
    }
}

/// Impacts the balance of user with the given `username` by the amount
/// described by `amount`. This function requires [`admin_user`](CCashUser) to
/// be the admin account for the CCash instance.
pub async fn impact_balance(
    session: &CCashSession,
    admin_user: &CCashUser,
    username: &str,
    amount: i64,
) -> Result<(), CCashError> {
    #[derive(serde::Serialize)]
    struct ImpactBalanceData {
        name: String,
        amount: i64,
    }

    let url = format!("{}/admin/impact_balance", &session.session_url);

    let body = ImpactBalanceData {
        name: username.into(),
        amount,
    };

    let r = request(Method::POST, session, &url, Some(admin_user), Some(&body)).await?;
    match r {
        CCashResponse::Success { .. } => Ok(()),
        CCashResponse::Error { .. } => Err(r.into()),
    }
}

/// Adds a [`user`](CCashUser) to the CCash session described by
/// [`session`](CCashSession) with the balance determined by `amount`. This
/// function requires that [`admin_user`](CCashUser) to be the admin account.
pub async fn add_user(
    session: &CCashSession,
    admin_user: &CCashUser,
    new_user: &CCashUser,
    amount: u32,
) -> Result<bool, CCashError> {
    #[derive(serde::Serialize)]
    struct AddUserData {
        #[serde(flatten)]
        user: CCashUser,
        amount: u32,
    }

    let url = format!("{}/admin/user/register", &session.session_url);

    let body = AddUserData {
        user: new_user.clone(),
        amount,
    };

    let r = request(Method::POST, session, &url, Some(admin_user), Some(&body)).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 a user associated with the `username` on the CCash instance
/// described by [`session`](CCashSession). This function requires that
/// [`admin_user`](CCashUser) to be the admin account for the CCash instance.
pub async fn delete_user(
    session: &CCashSession,
    admin_user: &CCashUser,
    username: &str,
) -> Result<(), CCashError> {
    let url = format!("{}/admin/user/delete", &session.session_url);
    let body = hash_map! { "name": username };

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

/// Prunes users with less than `amount` in balance or users with transactions
/// older than `time` and less than `amount` in balance. This function requires
/// that [`admin_user`](CCashUser) be the admin user for the CCash instance.
pub async fn prune_users(
    session: &CCashSession,
    admin_user: &CCashUser,
    amount: u32,
    time: Option<i64>,
) -> Result<u64, CCashError> {
    #[derive(serde::Serialize)]
    struct PruneUsersData {
        amount: u32,
        time: Option<i64>,
    }

    let url = format!("{}/admin/prune_users", &session.session_url);

    let body = PruneUsersData { time, amount };

    let r = request(Method::POST, session, &url, Some(admin_user), Some(&body)).await?;
    match r {
        CCashResponse::Success { .. } => Ok(r.convert_message::<u64>().unwrap()),
        CCashResponse::Error { .. } => Err(r.into()),
    }
}

/// Saves and closes the CCash instance. This updates [`session`](CCashSession)
/// to reflect that the connection to the CCash instance has closed. This
/// function requires that [`admin_user`](CCashUser) to be the admin user for
/// the CCash instance.
pub async fn close(
    session: &mut CCashSession,
    admin_user: &CCashUser,
) -> Result<(), CCashError> {
    let url = format!("{}/admin/shutdown", &session.session_url);

    let r = request::<()>(Method::POST, session, &url, Some(admin_user), None).await?;
    match r {
        CCashResponse::Success { .. } => {
            session.is_connected = false;
            session.client = None;
            session.properties = None;

            Ok(())
        },
        CCashResponse::Error { .. } => Err(r.into()),
    }
}