// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Authentication.OAuth;
using Microsoft.AspNet.Http;
using Microsoft.Framework.Internal;
using Newtonsoft.Json.Linq;
namespace Microsoft.AspNet.Authentication.MicrosoftAccount
{
///
/// Contains information about the login session as well as the user .
///
public class MicrosoftAccountAuthenticatedContext : OAuthAuthenticatedContext
{
///
/// Initializes a new .
///
/// The HTTP environment.
/// The JSON-serialized user.
/// The access token provided by the Microsoft authentication service.
public MicrosoftAccountAuthenticatedContext(HttpContext context, OAuthAuthenticationOptions options, [NotNull] JObject user, TokenResponse tokens)
: base(context, options, user, tokens)
{
IDictionary userAsDictionary = user;
JToken userId = User["id"];
if (userId == null)
{
throw new ArgumentException(Resources.Exception_MissingId, nameof(user));
}
Id = userId.ToString();
Name = PropertyValueIfExists("name", userAsDictionary);
FirstName = PropertyValueIfExists("first_name", userAsDictionary);
LastName = PropertyValueIfExists("last_name", userAsDictionary);
if (userAsDictionary.ContainsKey("emails"))
{
JToken emailsNode = user["emails"];
foreach (var childAsProperty in emailsNode.OfType().Where(childAsProperty => childAsProperty.Name == "preferred"))
{
Email = childAsProperty.Value.ToString();
}
}
}
///
/// Gets the Microsoft Account user ID.
///
public string Id { get; private set; }
///
/// Gets the user's name.
///
public string Name { get; private set; }
///
/// Gets the user's first name.
///
public string FirstName { get; private set; }
///
/// Gets the user's last name.
///
public string LastName { get; private set; }
///
/// Gets the user's email address.
///
public string Email { get; private set; }
private static string PropertyValueIfExists(string property, IDictionary dictionary)
{
return dictionary.ContainsKey(property) ? dictionary[property].ToString() : null;
}
}
}