// 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.IO;
using Microsoft.AspNetCore.Http.Authentication;
namespace Microsoft.AspNetCore.Authentication.Twitter
{
///
/// Serializes and deserializes Twitter request and access tokens so that they can be used by other application components.
///
public class RequestTokenSerializer : IDataSerializer
{
private const int FormatVersion = 1;
///
/// Serialize a request token.
///
/// The token to serialize
/// A byte array containing the serialized token
public virtual byte[] Serialize(RequestToken model)
{
using (var memory = new MemoryStream())
{
using (var writer = new BinaryWriter(memory))
{
Write(writer, model);
writer.Flush();
return memory.ToArray();
}
}
}
///
/// Deserializes a request token.
///
/// A byte array containing the serialized token
/// The Twitter request token
public virtual RequestToken Deserialize(byte[] data)
{
using (var memory = new MemoryStream(data))
{
using (var reader = new BinaryReader(memory))
{
return Read(reader);
}
}
}
///
/// Writes a Twitter request token as a series of bytes. Used by the method.
///
/// The writer to use in writing the token
/// The token to write
public static void Write(BinaryWriter writer, RequestToken token)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
if (token == null)
{
throw new ArgumentNullException(nameof(token));
}
writer.Write(FormatVersion);
writer.Write(token.Token);
writer.Write(token.TokenSecret);
writer.Write(token.CallbackConfirmed);
PropertiesSerializer.Default.Write(writer, token.Properties);
}
///
/// Reads a Twitter request token from a series of bytes. Used by the method.
///
/// The reader to use in reading the token bytes
/// The token
public static RequestToken Read(BinaryReader reader)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
if (reader.ReadInt32() != FormatVersion)
{
return null;
}
string token = reader.ReadString();
string tokenSecret = reader.ReadString();
bool callbackConfirmed = reader.ReadBoolean();
AuthenticationProperties properties = PropertiesSerializer.Default.Read(reader);
if (properties == null)
{
return null;
}
return new RequestToken { Token = token, TokenSecret = tokenSecret, CallbackConfirmed = callbackConfirmed, Properties = properties };
}
}
}