public void Setting_all_default_claims()
        {
            var fakeExpiration = new DateTimeOffset(2016, 01, 01, 12, 30, 00, TimeSpan.Zero);
            var fakeIssuedAt   = new DateTimeOffset(2015, 01, 01, 12, 30, 00, TimeSpan.Zero);
            var fakeNotBefore  = new DateTimeOffset(2015, 06, 01, 12, 30, 00, TimeSpan.Zero);

            this.builder
            .SetAudience("Count Dooku")
            .SetExpiration(fakeExpiration)
            .SetId("jwt-id")
            .SetIssuedAt(fakeIssuedAt)
            .SetIssuer("Lord Sidious")
            .SetNotBeforeDate(fakeNotBefore)
            .SetSubject("Secret Plans");

            var data = GetClaims(this.builder);

            data.ShouldContain(kvp => kvp.Key == "aud" && (string)kvp.Value == "Count Dooku");
            data.ShouldContain(kvp => kvp.Key == "exp" && UnixDate.FromLong((long)kvp.Value) == fakeExpiration);
            data.ShouldContain(kvp => kvp.Key == "jti" && (string)kvp.Value == "jwt-id");
            data.ShouldContain(kvp => kvp.Key == "iat" && UnixDate.FromLong((long)kvp.Value) == fakeIssuedAt);
            data.ShouldContain(kvp => kvp.Key == "iss" && (string)kvp.Value == "Lord Sidious");
            data.ShouldContain(kvp => kvp.Key == "nbf" && UnixDate.FromLong((long)kvp.Value) == fakeNotBefore);
            data.ShouldContain(kvp => kvp.Key == "sub" && (string)kvp.Value == "Secret Plans");
        }
Пример #2
0
        public static Comment ParseJson(JToken json)
        {
            var comment = new Comment();

            comment.Id = Json.TryGetJsonProperty(json, "id");
            Debug.Assert(comment.Id != null);

            comment.User = CompactUser.ParseJson(json["user"]);

            comment.Text = Json.TryGetJsonProperty(json, "text");

            if (comment.User != null)
            {
                comment.IsSelf = comment.User.Relationship == FriendStatus.Self;
            }

            string created = Json.TryGetJsonProperty(json, "createdAt");

            if (created != null)
            {
                DateTime dtc = UnixDate.ToDateTime(created);
                comment.CreatedDateTime = dtc;
                comment.Created         = Checkin.GetDateString(dtc);
            }

            return(comment);
        }
Пример #3
0
        public static Todo ParseJson(JToken json)
        {
            Todo   todo = new Todo();
            string id   = Json.TryGetJsonProperty(json, "id");

            string created = Json.TryGetJsonProperty(json, "createdAt");

            if (created != null)
            {
                DateTime dtc = UnixDate.ToDateTime(created);
                //t.CreatedDateTime = dtc;
                todo.Created = Checkin.GetDateString(dtc);
            }

            var tipJson = json["tip"];

            if (tipJson != null)
            {
                var tip = Tip.ParseJson(tipJson);
                if (tip != null)
                {
                    if (todo.Created != null)
                    {
                        tip.OverrideAddedText = "added " + todo.Created + (
                            tip.User != null ? (" (via " + tip.User.ToString() + ")") : string.Empty);
                    }

                    todo.Tip = tip;
                }
            }

            todo.TodoId = id;

            return(todo);
        }
Пример #4
0
        public void Dec_31_2012_is_1356134399()
        {
            var endOfMayanLongCountCycle = new DateTimeOffset(2012, 12, 21, 23, 59, 59, TimeSpan.Zero);

            // Editor's note: World did not cataclysmically end on this date.
            UnixDate.ToLong(endOfMayanLongCountCycle).ShouldBe(1356134399);
        }
Пример #5
0
        public static Update ParseJson(JToken update)
        {
            Update u = new Update();

            string created = Json.TryGetJsonProperty(update, "createdAt");

            if (created != null)
            {
                int i;
                if (int.TryParse(created, out i))
                {
                    u.CreatedAt = i;
                }

                // FUTURE: Consider an option to NOT include people in the checkin list who have not checked in within the last month. (perf default!)
                DateTime dtc = UnixDate.ToDateTime(created);
                u.CreatedDateTime = dtc;
                u.Created         = Checkin.GetDateString(dtc);
            }

            // unread
            u.IsUnread = Json.TryGetJsonBool(update, "unread");

            // ids
            var idj = update["ids"];

            if (idj != null)
            {
                u.Ids = idj.Values <string>().ToList();
            }

            // target
            var targetJson = update["target"];

            if (targetJson != null)
            {
                u.TargetObject = TargetObject.ParseJson(targetJson);
            }

            // text
            u.Text = Json.TryGetJsonProperty(update, "text");

            // entities

            // image
            var img = update["image"];

            if (img != null)
            {
                u.FullImage = Json.TryGetUriProperty(img, "fullPath");
            }

            // imageType

            // [icon]

            return(u);
        }
Пример #6
0
        public HeaderBlock(UnixDate timeStamp, string description)
        {
            description.Verify(nameof(description)).IsNotEmpty();

            TimeStamp   = timeStamp;
            Description = description;

            Digest = GetDigest();
        }
Пример #7
0
        public void Unix_1435665600_is_noon_June_30_2015()
        {
            var june30Noon = UnixDate.FromLong(1435665600);

            june30Noon.Year.ShouldBe(2015);
            june30Noon.Month.ShouldBe(6);
            june30Noon.Day.ShouldBe(30);
            june30Noon.Hour.ShouldBe(12);
            june30Noon.Minute.ShouldBe(00);
            june30Noon.Second.ShouldBe(00);
        }
Пример #8
0
        public void GivenHeaderBlock_WhenCloned_ShouldValidate()
        {
            UnixDate now = UnixDate.UtcNow;

            var subject = new HeaderBlock(now, "Text-2222");

            subject.Digest.Should().NotBeNullOrEmpty();

            var s1 = new HeaderBlock(subject.TimeStamp, subject.Description);

            subject.Digest.Should().Be(subject.GetDigest());
        }
Пример #9
0
 public DataBlock(UnixDate timeStamp,
                  string blockType,
                  string blockId,
                  T data,
                  IEnumerable <KeyValuePair <string, string> >?properties = null,
                  string?digest       = null,
                  string?jwtSignature = null)
     : this(blockType, blockId, data, properties)
 {
     TimeStamp    = timeStamp;
     Digest       = digest ?? Digest;
     JwtSignature = jwtSignature;
 }
Пример #10
0
        public void GivenHeaderBlock_WhenSameInitialized_ShouldValidate()
        {
            UnixDate now = UnixDate.UtcNow;

            var subject = new HeaderBlock(now, "Text-1111");

            subject.Digest.Should().NotBeNullOrEmpty();

            var s1 = new HeaderBlock(now, "Text-1111");

            s1.Digest.Should().NotBeNullOrEmpty();

            subject.Digest.Should().Be(s1.Digest);
        }
Пример #11
0
        public void GivenBlobBlock_WhenCloned_ShouldValidate()
        {
            UnixDate             now     = UnixDate.UtcNow;
            IReadOnlyList <byte> payload = "This is a test of the blob - GivenHeaderBlock_WhenCloned_ShouldValidate".ToBytes();

            var subject = new BlobBlock("blockName1", "xlsx", "you", payload);

            subject.Digest.Should().NotBeNullOrEmpty();

            var s1 = new BlobBlock(subject.Name, subject.ContentType, subject.Author, subject.Content);

            s1.Digest.Should().Be(s1.GetDigest());

            s1.Digest.Should().Be(subject.Digest);
            (subject == s1).Should().BeTrue();
        }
Пример #12
0
        public void GivenBlobBlock_WhenSameInitialized_ShouldValidate()
        {
            UnixDate now = UnixDate.UtcNow;

            IReadOnlyList <byte> payload = "This is a test of the blob - GivenHeaderBlock_WhenSameInitialized_ShouldValidate".ToBytes();

            var subject = new BlobBlock("blockName", "docx", "me", payload);

            subject.Digest.Should().NotBeNullOrEmpty();

            var s1 = new BlobBlock("blockName", "docx", "me", payload);

            s1.Digest.Should().NotBeNullOrEmpty();

            subject.Digest.Should().Be(s1.Digest);
        }
Пример #13
0
        public void GivenDate_WhenUsedWithType_ShouldPass()
        {
            UnixDate d1 = UnixDate.UtcNow;
            UnixDate d2 = d1;

            d2.TimeStamp.Should().Be(d1.TimeStamp);

            long v1 = d1.TimeStamp;

            v1.Should().Be(d2.TimeStamp);

            UnixDate d3 = (UnixDate)v1;

            d3.TimeStamp.Should().Be(v1);

            UnixDate d4 = v1.ToUnixDate();
        }
        public static CheckinResponse ParseJson(JToken json)
        {
            var r = new CheckinResponse();

            var tt = new TombstoningText("response");

            tt.Text = json.ToString();
            tt.Save(r.UniqueId);

            try
            {
                var checkin = json["checkin"]; // (JArray)json["checkin"];
                // string type = Json.TryGetJsonProperty(checkin, "type");
                // checkin,shout,venueless

                string created = Json.TryGetJsonProperty(checkin, "createdAt");
                if (created != null)
                {
                    DateTime dtc = UnixDate.ToDateTime(created);
                    r.Created = dtc;
                }

                r.CheckinId = Json.TryGetJsonProperty(checkin, "id");

                var venue = checkin["venue"];
                if (venue != null)
                {
                    r.Venue = CompactVenue.ParseJson(venue);
                }

                return(r);
            }
            catch (Exception e)
            {
                throw new UserIntendedException(
                          "There was a problem trying to check-in, please try again later.", e);
            }
        }
        private DateTimeOffset?GetDateClaim(string claimName)
        {
            object value = this.AsInterface.GetClaim(claimName);

            if (value == null)
            {
                return(null);
            }

            try
            {
                var unixTimestamp = Convert.ToInt64(value);
                return(UnixDate.FromLong(unixTimestamp));
            }
            catch (FormatException)
            {
                return(null);
            }
            catch (OverflowException)
            {
                return(null);
            }
        }
Пример #16
0
        public static Tip ParseJson(JToken tip, Type parentType, string parentIdentifier)
        {
            var t = new Tip();

            t.ParentType       = parentType;
            t.ParentIdentifier = parentIdentifier;

            t.TipId = Json.TryGetJsonProperty(tip, "id");
            Debug.Assert(t.TipId != null);

            string txt = Checkin.SanitizeString(Json.TryGetJsonProperty(tip, "text"));

            if (!string.IsNullOrEmpty(txt))
            {
                t.Text = txt;
            }

            var user = tip["user"];

            if (user != null)
            {
                t.User = CompactUser.ParseJson(user);
            }

            string created = Json.TryGetJsonProperty(tip, "createdAt");

            if (created != null)
            {
                DateTime dtc = UnixDate.ToDateTime(created);
                t.CreatedDateTime = dtc;
                t.Created         = Checkin.GetDateString(dtc);
            }

            // NOTE: Consider getting tip group details. Only available in the
            // request. Would be a nice future release update probably.

            var todoCount = tip["todo"];

            if (todoCount != null)
            {
                string cc = Json.TryGetJsonProperty(todoCount, "count");
                int    i;
                if (int.TryParse(cc, out i))
                {
                    t.TodoCount = i;
                }
            }

            var doneCount = tip["done"];

            if (doneCount != null)
            {
                string cc = Json.TryGetJsonProperty(doneCount, "count");
                int    i;
                if (int.TryParse(cc, out i))
                {
                    t.DoneCount = i;
                }
            }

            if (t.DoneCount <= 0)
            {
                t.DoneText = "No one has done this.";
            }
            else if (t.DoneCount == 1)
            {
                t.DoneText = "1 person has done this.";
            }
            else
            {
                t.DoneText = t.DoneCount.ToString(CultureInfo.InvariantCulture) + " people have done this.";
            }

            var photo = tip["photo"];

            if (photo != null)
            {
                var pht = Model.Photo.ParseJson(photo);
                if (pht != null)
                {
                    t.Photo = pht;
                }
            }

            string status = Json.TryGetJsonProperty(tip, "status");

            //Debug.WriteLine("tip status read as (temp): " + status);
            t.Status = TipStatus.None;
            if (status != null)
            {
                if (status == "done")
                {
                    t.Status     = TipStatus.Done;
                    t.StatusText = "You've done this!";
                }
                else if (status == "todo")
                {
                    t.Status     = TipStatus.Todo;
                    t.StatusText = "You need to do this!";

                    // Don't tell the user nobody has done this if it's just them.
                    if (t.DoneCount <= 0)
                    {
                        t.DoneText = null;
                    }
                }
            }

            var compactVenue = tip["venue"];

            if (compactVenue != null)
            {
                t.Venue = CompactVenue.ParseJson(compactVenue);
            }

            string parentTypeText = t.ParentType == typeof(Model.Venue) ? "venue" : null;

            if (parentTypeText == null)
            {
                if (t.ParentType == typeof(Model.UserTips))
                {
                    parentTypeText = "usertips";
                }
                else if (t.ParentType == typeof(RecommendedTipNotification) || t.ParentType == typeof(DetailedTip))
                {
                    parentTypeText = "direct";
                }
                else
                {
                    parentTypeText = "unknown";
                }
            }

            Uri tipUri = new Uri(
                string.Format(
                    CultureInfo.InvariantCulture,
                    "/JeffWilcox.FourthAndMayor.Lists;component/ListItem.xaml?id={0}&tipId={0}",
                    Uri.EscapeDataString(t.TipId))
                , UriKind.Relative);

            t.TipUri = tipUri;

            // TODO: This supports todo w/count, done w/count, ...

            return(t);
        }
Пример #17
0
        public static Photo ParseJson(JToken json)
        {
            Photo p = new Photo();

            p.Id = Json.TryGetJsonProperty(json, "id");
            //Debug.Assert(p.Id != null);

            string created = Json.TryGetJsonProperty(json, "createdAt");

            if (created != null)
            {
                DateTime dtc = UnixDate.ToDateTime(created);
                p.CreatedDateTime = dtc;
                p.Created         = Checkin.GetDateString(dtc);
            }

            string primaryUri = Json.TryGetJsonProperty(json, "url");

            if (primaryUri != null)
            {
                p.Uri = new Uri(primaryUri, UriKind.Absolute);
            }

            var userJson = json["user"];

            if (userJson != null)
            {
                p.User = CompactUser.ParseJson(userJson);
                if (p.User != null)
                {
                    p.IsSelf = p.User.Relationship == FriendStatus.Self;
                }
            }

            var sizes = json["sizes"];

            if (sizes != null)
            {
                var items = sizes["items"];
                List <UriWidthHeight> sz = new List <UriWidthHeight>();
                foreach (var item in items)
                {
                    sz.Add(new UriWidthHeight
                    {
                        Uri    = new Uri(Json.TryGetJsonProperty(item, "url"), UriKind.Absolute),
                        Width  = double.Parse(Json.TryGetJsonProperty(item, "width"), CultureInfo.InvariantCulture),
                        Height = double.Parse(Json.TryGetJsonProperty(item, "height"), CultureInfo.InvariantCulture),
                    });
                }
                if (sz.Count > 0)
                {
                    p.SmallestUri = sz[sz.Count - 1].Uri;
                    p.MediumUri   = sz[sz.Count > 2 ? sz.Count - 2 : sz.Count - 1].Uri;
                    p.LargerUri   = sz[1].Uri;
                }
            }

            Uri pu = new Uri(
                string.Format(
                    CultureInfo.InvariantCulture,
                    "/Views/PhotoViewer.xaml?photoUri={0}&isSelf={1}&id={2}",

                    Uri.EscapeDataString(p.Uri.ToString()),
                    p.IsSelf ? "true" : "false",
                    p.Id
                    )
                , UriKind.Relative);

            p.LocalPhotoViewerUri = pu;

            return(p);
        }
Пример #18
0
        public static CompactListItem ParseJson(JToken json)
        {
            CompactListItem c = new CompactListItem();

            c.Id = Json.TryGetJsonProperty(json, "id");

            string created = Json.TryGetJsonProperty(json, "createdAt");

            if (created != null)
            {
                DateTime dtc = UnixDate.ToDateTime(created);
                c.CreatedAt = Checkin.GetDateString(dtc);
                c.Created   = dtc;
            }

            var user = json["user"];

            if (user != null)
            {
                c.User = CompactUser.ParseJson(user);
            }

            var photo = json["photo"];

            if (photo != null)
            {
                c.Photo = Photo.ParseJson(photo);
            }

            var venue = json["venue"];

            if (venue != null)
            {
                c.Venue = CompactVenue.ParseJson(venue);
            }

            var tip = json["tip"];

            if (tip != null)
            {
                c.Tip = Tip.ParseJson(tip);
            }

            var note = json["note"];

            if (note != null)
            {
                c.Note = Json.TryGetJsonProperty(note, "text");
            }

            c.Todo   = Json.TryGetJsonBool(json, "todo");
            c.IsDone = Json.TryGetJsonBool(json, "done");

            string s = Json.TryGetJsonProperty(json, "visitedCount");

            if (s != null)
            {
                int i;
                if (int.TryParse(s, out i))
                {
                    c.VisitedCount = i;
                }
            }

            // TODO: V4: "listed" list of compact venues where the item appears on.

            return(c);
        }
Пример #19
0
        public static Checkin ParseJson(JToken checkin)
        {
            Checkin c = new Checkin();

            string created = Json.TryGetJsonProperty(checkin, "createdAt");

            if (created != null)
            {
                // FUTURE: Consider an option to NOT include people in the checkin list who have not checked in within the last month. (perf default!)
                DateTime dtc = UnixDate.ToDateTime(created);
                c.CreatedDateTime = dtc;
                c.Created         = GetDateString(dtc);
            }

            // Client information.
            var source = checkin["source"];

            if (source != null)
            {
                c.ClientName = Json.TryGetJsonProperty(source, "name");

                // TODO: Create a crashless URI helper.
                try
                {
                    string url = Json.TryGetJsonProperty(source, "url");
                    if (!string.IsNullOrEmpty(url))
                    {
                        if (url.StartsWith("www"))
                        {
                            url = "http://" + url;
                        }
                        c.ClientWebUri = new Uri(url, UriKind.Absolute);
                    }
                }
                catch
                {
                }
            }

            string type = Json.TryGetJsonProperty(checkin, "type");

            // Only if present. Won't show up in badge winnings, for instance.
            if (type != null)
            {
                Debug.Assert(type == "checkin" || type == "shout" || type == "venueless");
            }
            c.CheckinType = type;

            c.CheckinId = Json.TryGetJsonProperty(checkin, "id");
            // badge mode actually won't have this Debug.Assert(c.CheckinId != null);

            if (!string.IsNullOrEmpty(c.CheckinId))
            {
                c.LocalCommentsUri = new Uri(string.Format(CultureInfo.InvariantCulture, "/Views/Comments.xaml?checkin={0}", c.CheckinId), UriKind.Relative);
            }

            var location = checkin["location"];

            if (location != null && type == "venueless") // consider if that's right
            {
                // if shout or venueless, will provide...
                // lat, lng pair and/or a name
                string venuelessName = Json.TryGetJsonProperty(location, "name");
                c.VenuelessName = venuelessName;
            }

            var user = checkin["user"];

            if (user != null)
            {
                CompactUser bu = CompactUser.ParseJson(user);
                c.User = bu;
            }

            var venue = checkin["venue"];

            if (venue != null)
            {
                CompactVenue bv = CompactVenue.ParseJson(venue);
                if (bv != null)
                {
                    c.DisplayAddressLine = bv.AddressLine;
                }
                c.Venue = bv;
            }

            // Show venueless name at least.
            if (c.Venue == null && !string.IsNullOrEmpty(c.VenuelessName))
            {
                c.Venue = CompactVenue.CreateVenueless(c.VenuelessName);
            }

            c.Shout = Json.TryGetJsonProperty(checkin, "shout");

            string ismayor = Json.TryGetJsonProperty(checkin, "isMayor");

            if (ismayor != null && ismayor.ToLowerInvariant() == "true")
            {
                c.IsMayor = true;
            }

            string dist = Json.TryGetJsonProperty(checkin, "distance");

            if (dist == null)
            {
                c.Meters = double.NaN;
            }
            else
            {
                c.Meters = double.Parse(dist, CultureInfo.InvariantCulture);

                // Doing this here to centralize it somewhere at least.
                if (c.Meters > 40000) // NOTE: This is a random value, What value should define a different city?
                {
                    c.IsInAnotherCity = true;
                    if (c.Venue != null)
                    {
                        string s = c.Venue.City ?? string.Empty;
                        if (!string.IsNullOrEmpty(c.Venue.State))
                        {
                            s += ", ";
                        }
                        if (c.Venue.State != null)
                        {
                            s += c.Venue.State;
                        }

                        c.DisplayAddressLine = s;
                    }
                }
            }

            if (c.User != null)
            {
                c.DisplayUser = c.User.ShortName;
                c.UserUri     = c.User.UserUri;
            }
            if (c.Venue != null)
            {
                c.DisplayBetween = null; // WAS:  "@";
                c.DisplayVenue   = c.Venue.Name;
                c.VenueUri       = c.Venue.VenueUri;
            }
            else
            {
                if (type == "shout")
                {
                    //c.DisplayBetween = "shouted:";
                }
                else if (type == "venueless")
                {
                    c.DisplayBetween = c.VenuelessName;
                }
                else
                {
                    c.DisplayBetween = "[off-the-grid]"; // @
                }
            }

            // Photo and Comment information
            c.CommentsCount = GetNodeCount(checkin, "comments");
            c.PhotosCount   = GetNodeCount(checkin, "photos");

            c.HasComments         = c.CommentsCount > 0;
            c.HasPhotos           = c.PhotosCount > 0;
            c.HasPhotosOrComments = c.HasComments || c.HasPhotos;

            if (c.HasPhotos)
            {
                List <Photo> photos = new List <Photo>();
                var          pl     = checkin["photos"];
                if (pl != null)
                {
                    var pll = pl["items"];
                    if (pll != null)
                    {
                        foreach (var photo in pll)
                        {
                            var po = Photo.ParseJson(photo);
                            if (po != null)
                            {
                                photos.Add(po);
                            }
                        }
                    }
                }
                c.Photos = photos;

                if (photos.Count > 0)
                {
                    c.FirstCheckinPhoto = photos[0];
                }
            }

            int activityCount = c.CommentsCount; // +c.PhotosCount;

            c.CommentsAndPhotosOrAdd = activityCount > 0 ? activityCount.ToString(CultureInfo.InvariantCulture) : "+";

            if (c.User != null && c.User.Relationship == FriendStatus.Self)
            {
                c.CanAddPhotos = true;
            }

            return(c);
        }
Пример #20
0
 IJwtClaimsBuilder IClaimsMutator <IJwtClaimsBuilder> .SetNotBeforeDate(DateTimeOffset?nbf)
 {
     this.SetOrRemove(DefaultJwtClaims.NotBefore, UnixDate.ToLong(nbf));
     return(this);
 }
Пример #21
0
 IJwtClaimsBuilder IClaimsMutator <IJwtClaimsBuilder> .SetIssuedAt(DateTimeOffset?iat)
 {
     this.SetOrRemove(DefaultJwtClaims.IssuedAt, UnixDate.ToLong(iat));
     return(this);
 }
Пример #22
0
 IJwtClaimsBuilder IClaimsMutator <IJwtClaimsBuilder> .SetExpiration(DateTimeOffset?exp)
 {
     this.SetOrRemove(DefaultJwtClaims.Expiration, UnixDate.ToLong(exp));
     return(this);
 }
Пример #23
0
        public void Start_of_Unix_epoch_is_zero()
        {
            var epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);

            UnixDate.ToLong(epoch).ShouldBe(0);
        }