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
//! Payload

use api::types::*;
use api::product::*;
use api::user::User;
use api::client::Client;
use api::mfa;

use rustc_serialize::{Encodable, Encoder};

use hyper::method::Method;

/// Use this enum to tell the client what you want to do
/// with the associated product.
pub enum Payload<'a> {
    /// Authenticate a user.
    Authenticate(Client<'a>, Institution, Username, Password, Option<PIN>, Option<AuthenticateOptions>),
    /// Re-euthenticate an existing user.
    Reauthenticate(Client<'a>, Institution, Username, Password, Option<PIN>, Option<AuthenticateOptions>),
    /// Upgrade the user for access to the given product.
    Upgrade(Client<'a>, User, Option<AuthenticateOptions>),
    /// Delete a user from Plaid.
    RemoveUser(Client<'a>, User),
    /// Send multifactor authentication response.
    StepMFA(Client<'a>, User, mfa::Response),
    /// Retrieve data from the product.
    FetchData(Client<'a>, User, Option<FetchDataOptions>)
}

impl<'a> Payload<'a> {

    /// Returns the desired endpoint of the payload, given a `Product`
    pub fn endpoint<P: Product>(&self, client: &'a Client<'a>, product: P) -> String {
        format!("{}{}", client.endpoint, product.endpoint(&self))
    }

    /// Returns the `hyper::method::Method` to be used for the request
    pub fn method(&self) -> Method {
        match *self {
            Payload::Authenticate(..) => Method::Post,
            Payload::Reauthenticate(..) => Method::Patch,
            Payload::Upgrade(..) => Method::Post,
            Payload::RemoveUser(..) => Method::Delete,
            Payload::StepMFA(..) => Method::Patch,
            Payload::FetchData(..) => Method::Get,
        }
    }

}

impl<'a> Encodable for Payload<'a> {

    fn encode<S: Encoder>(&self, encoder: &mut S) -> Result<(), S::Error> {
        match *self {
            Payload::Authenticate(ref client, ref institution, ref username, ref password, ref pin, ref options) |
            Payload::Reauthenticate(ref client, ref institution, ref username, ref password, ref pin, ref options) => {
                let fields = if pin.is_some() { 7 } else { 6 };
                encoder.emit_struct("Request", fields, |encoder| {
                    try!(encoder.emit_struct_field("client_id", 0, |e| client.client_id.encode(e)));
                    try!(encoder.emit_struct_field("secret", 1, |e| client.secret.encode(e)));
                    try!(encoder.emit_struct_field("username", 2, |e| username.encode(e)));
                    try!(encoder.emit_struct_field("password", 3, |e| password.encode(e)));
                    try!(encoder.emit_struct_field("type", 4, |e| institution.encode(e)));
                    try!(encoder.emit_struct_field("options", 5, |e| options.encode(e)));
                    if pin.is_some() { try!(encoder.emit_struct_field("pin", 6, |e| pin.encode(e))); }

                    Ok(())
                })
            },
            Payload::Upgrade(ref client, ref user, ref options) => {
                encoder.emit_struct("Request", 1, |encoder| {
                    try!(encoder.emit_struct_field("client_id", 0, |e| client.client_id.encode(e)));
                    try!(encoder.emit_struct_field("secret", 1, |e| client.secret.encode(e)));
                    try!(encoder.emit_struct_field("access_token", 2, |e| user.access_token.encode(e)));
                    try!(encoder.emit_struct_field("options", 0, |e| options.encode(e)));
                    Ok(())
                })
            },
            Payload::StepMFA(ref client, ref user, ref mfa_response) => {
                encoder.emit_struct("Request", 4, |encoder| {
                    try!(encoder.emit_struct_field("client_id", 0, |e| client.client_id.encode(e)));
                    try!(encoder.emit_struct_field("secret", 1, |e| client.secret.encode(e)));
                    try!(encoder.emit_struct_field("access_token", 2, |e| user.access_token.encode(e)));
                    try!(encoder.emit_struct_field("mfa", 3, |e| mfa_response.encode(e)));
                    Ok(())
                })
            },
            Payload::FetchData(ref client, ref user, Some(ref options)) => {
                encoder.emit_struct("Request", 1, |encoder| {
                    try!(encoder.emit_struct_field("client_id", 0, |e| client.client_id.encode(e)));
                    try!(encoder.emit_struct_field("secret", 1, |e| client.secret.encode(e)));
                    try!(encoder.emit_struct_field("access_token", 2, |e| user.access_token.encode(e)));
                    try!(encoder.emit_struct_field("options", 0, |e| options.encode(e)));
                    Ok(())
                })
            },
            _ => Ok(())
        }
    }

}

/// The device that the user has chosen to use for mfa.
#[derive(Debug)]
pub enum SelectedDevice {
    /// The `mask` returned when authenticating with `AuthenticateOptions { list: true, .. }`,
    /// e.g "[email protected]",
    Mask(String),
    /// The type of the device as defined under `mfa::Device`.
    Device(mfa::Device)
}

impl Encodable for SelectedDevice {

    fn encode<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
        e.emit_struct("root", 1, |e| {
            match *self {
                SelectedDevice::Device(ref d) => e.emit_struct_field("type", 0, |e| d.encode(e)),
                SelectedDevice::Mask(ref m) => e.emit_struct_field("mask", 0, |e| m.encode(e))
            }
        })
    }

}

/// Options that can be passed along to any `Payload::Authenticate` request.
#[derive(Debug, RustcEncodable)]
pub struct AuthenticateOptions {
    /// A webhook that should be used by Plaid when events are generated.
    webhook: Option<String>,
    /// If `true`, initial data will not be fetched
    login_only: Option<bool>,
    /// If `true`, a list of possible mfa devices will be presented.
    /// If `false`, the first possible device will already be chosen for the user.
    list: Option<bool>,
    /// If specified, this will select the given `SelectedDevice::Mask` or `SelectedDevice::Device`
    /// for use in multifactor authentication.
    send_method: Option<SelectedDevice>
}

impl AuthenticateOptions {

    /// Generate a default `AuthenticateOptions` struct with every field unset.
    pub fn default() -> AuthenticateOptions {
        AuthenticateOptions {
            webhook: None,
            login_only: None,
            list: None,
            send_method: None
        }
    }

}

/// Options that can be passed along to any `Payload::FetchData` request.
#[derive(Debug, RustcEncodable)]
pub struct FetchDataOptions {
    /// This will filter out transactions that have occured before the given `Date`
    start_date: Option<Date>,
    /// This will filter out transactions that have occured after the given `Date`
    end_date: Option<Date>
}

impl FetchDataOptions {

    /// Generate a default `FetchDataOptions` struct with every field unset.
    pub fn default() -> FetchDataOptions {
        FetchDataOptions {
            start_date: None,
            end_date: None
        }
    }

}

#[cfg(test)]
mod tests {

    use api::user::User;
    use api::client::{ Client, Payload };
    use api::client::payload::{ FetchDataOptions,  AuthenticateOptions };
    use rustc_serialize::json;
    use hyper as h;

    #[test]
    fn test_authenticate_payload_serialization() {
        let hyper = h::Client::new();
        let client = Client { endpoint: "https://tartan.plaid.com",
                              client_id: "testclientid",
                              secret: "testsecret",
                              hyper: &hyper };

        assert_eq!(json::encode(
            &Payload::Authenticate(
                client,
                "testinst".to_string(),
                "username".to_string(),
                "password".to_string(),
                Some("PINCODE".to_string()),
                Some(AuthenticateOptions { list: Some(true), .. AuthenticateOptions::default() }))).unwrap(),
                r###"{"client_id":"testclientid","secret":"testsecret","username":"username","password":"password","type":"testinst","options":{"webhook":null,"login_only":null,"list":true,"send_method":null},"pin":"PINCODE"}"###)
    }

    #[test]
    fn test_fetch_data_payload_serialization() {
        let hyper = h::Client::new();
        let user = User { access_token: "accesstoken123".to_string() };
        let client = Client { endpoint: "https://tartan.plaid.com",
                              client_id: "testclientid",
                              secret: "testsecret",
                              hyper: &hyper };

        assert_eq!(json::encode(
            &Payload::FetchData(
                client,
                user,
                Some(FetchDataOptions { start_date: Some("2015-01-01".to_string()), end_date: Some("2016-01-01".to_string()) }))).unwrap(),
            r###"{"client_id":"testclientid","secret":"testsecret","access_token":"accesstoken123""options":{"start_date":"2015-01-01","end_date":"2016-01-01"}}"###)
    }

}