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
//! This module defines several types and provides some low-level functions.

use chrono::datetime::{DateTime};
use chrono::naive::datetime::{NaiveDateTime};
use chrono::offset::utc::{UTC};
use rustc_serialize::{Decodable, Decoder, Encodable, Encoder, json};
use rustc_serialize::json::{Json};
use std::ops::Deref;

/// Abstraction for a type wrapper around a generic type.
///
/// It is helpful to put application-specific type wrappers around generic
/// types.  For example, `UserId` and `SessinoId` are really `String` values.
/// But wrapping them in specific types allows to compiler to catch errors, such
/// as arguments that are given in the wrong order.
pub trait Newtype<T: Deref> {
    fn unwrap(self) -> T;
    fn as_slice(&self) -> &<T as Deref>::Target;
}

macro_rules! typed_string {
    ($t:ident) => (
        #[derive(PartialEq, Eq, Clone, Debug)]
        pub struct $t(String);

        impl $t {
            pub fn new(s: String) -> $t {
                $t(s)
            }

            pub fn from_slice(s: &str) -> $t {
                $t(s.to_string())
            }
        }

        impl Newtype<String> for $t {
            fn unwrap(self) -> String {
                let $t(v) = self;
                v
            }
            fn as_slice(&self) -> &str {
                let &$t(ref v) = self;
                v.as_slice()
            }
        }

        impl Decodable for $t {
            fn decode<D: Decoder>(d: &mut D) -> Result<$t, D::Error> {
                d.read_str().map($t::new)
            }
        }

        impl Encodable for $t {
            fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
                s.emit_str(self.as_slice())
            }
        }

        impl json::ToJson for $t {
            fn to_json(&self) -> Json {
                Json::String(self.as_slice().to_string())
            }
        }
    )
}

/// Value that will be an input in signature made by the Tozny app
typed_string!(Challenge);

/// Type for realm key ids
///
/// A realm key id identifies a realm; and when paired with its corresponding
/// secret acts as a credential to make realm-level API calls.
typed_string!(KeyId);

/// When making an API call, specifies which API method will be invoked.
typed_string!(Method);

/// Token that matches up with a specific mobile device.
///
/// A `Presence` value is used to send a push notification to a device, so that
/// the user does not have to scan a QR code.  The response from the
/// `login_challenge` method on `UserApi` includes a `Presence` value.  Store
/// the value to keep track of which device was last used to log into an
/// account.
typed_string!(Presence);

/// Shared secret that proves ownership of a realm key.
typed_string!(Secret);

/// Generated by Tozny; matches a successful authentication event with an
/// application session.
///
/// The response from the `login_challenge` method on `UserApi` includes
/// a `SessionId`.  Use that value when calling `check_session_status` to
/// determine whether the user has authenticated.
typed_string!(SessionId);

/// Specifies which cryptographic algorithm was used to sign a message.
typed_string!(SignatureType);

/// Identifies a Tozny user.
typed_string!(UserId);

/// Wraps a `DateTime<UTC>` value; implements serialization into the format
/// expected by the Tozny API.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Timestamp(DateTime<UTC>);

impl Timestamp {
    pub fn new(t: DateTime<UTC>) -> Timestamp {
        Timestamp(t)
    }

    pub fn unwrap(self) -> DateTime<UTC> {
        let Timestamp(t) = self;
        t
    }

    pub fn as_slice(&self) -> &DateTime<UTC> {
        let &Timestamp(ref t) = self;
        t
    }
}

fn int_to_timestamp(seconds: i64) -> Timestamp {
    let naive = NaiveDateTime::from_num_seconds_from_unix_epoch(seconds, 0);
    Timestamp(DateTime::from_utc(naive, UTC))
}

impl Decodable for Timestamp {
    fn decode<D: Decoder>(d: &mut D) -> Result<Timestamp, D::Error> {
        d.read_i64().map(int_to_timestamp)
    }
}

/// Given a time, produces a string representing that time as the number of
/// seconds since January 1, 1970.
impl Encodable for Timestamp {
    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
        let &Timestamp(ref t) = self;
        let seconds = t.num_seconds_from_unix_epoch();
        s.emit_i64(seconds)
    }
}

impl json::ToJson for Timestamp {
    fn to_json(&self) -> Json {
        Json::I64(self.as_slice().num_seconds_from_unix_epoch())
    }
}

/// Extracts error messages from a Tozny API response.
pub fn error_response(json: &Json) -> Option<&Json> {
    json.find("return")
    .and_then(|val| { val.as_string() })
    .and_then(|ret| {
        if ret == "error" {
            json.find("errors")
        }
        else {
            None
        }
    })
}