using System;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace NPSharp.Authentication
{
public class AuthenticationHelper
{
private string _path;
private ushort _port;
private string _host;
///
/// Gets the username.
///
/// The username.
public string Username { get; private set; }
///
/// Gets the user's e-mail address.
///
/// The user's e-mail address.
public string UserEMail { get; private set; }
///
/// Gets the session token.
///
/// The session token.
public string SessionToken { get; private set; }
///
/// Gets the user identifier.
///
/// The user identifier.
public uint UserId { get; private set; }
///
/// Initializes a new instance of the class.
///
/// Hostname of the authentication endpoint.
/// Port of the authentication endpoint.
/// Path of the authentication endpoint.
public AuthenticationHelper (string host, ushort port = 12003, string path = "/authenticate")
{
_host = host;
_port = port;
_path = path;
}
///
/// Authenticate the specified username and password.
///
/// The username to use for authentication.
/// The password to use for authentication.
public void Authenticate (string username, string password)
{
var post = string.Format ("{0}&&{1}", username, password);
var uri = new UriBuilder {
Scheme = "http",
Port = _port,
Host = _host,
Path = _path
}.Uri;
var req = (HttpWebRequest)WebRequest.Create(uri);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.AllowAutoRedirect = true;
using (var reqStream = req.GetRequestStream()) {
var buffer = Encoding.UTF8.GetBytes (post);
reqStream.Write (buffer, 0, post.Length);
reqStream.Flush ();
}
// Response will be in this syntax:
// (ok|fail)#text#userid#username#email#sessiontoken
var rx = new Regex("^(?ok|fail)#(?.+)#(?[0-9]+)#(?.+)#(?.+)#(?.+)$");
var resp = (HttpWebResponse)req.GetResponse ();
using (var respStream = resp.GetResponseStream()) {
using (var respReader = new StreamReader(respStream)) {
while (!respReader.EndOfStream) {
var line = respReader.ReadLine ();
// DW response line found?
if (!rx.IsMatch (line))
continue;
// This is a DW response line, analyze
var rxm = rx.Match (line);
// Login succeeded?
if (rxm.Groups ["status"].Value != "ok")
throw new Exception (rxm.Groups ["text"].Value);
// Store all data
Username = rxm.Groups ["username"].Value;
UserEMail = rxm.Groups ["usermail"].Value;
SessionToken = rxm.Groups ["sessiontoken"].Value;
UserId = uint.Parse (rxm.Groups ["userid"].Value);
}
}
}
}
}
}