Added BitId login

This commit is contained in:
Rick Falkvinge
2014-10-30 15:31:04 +01:00
parent b2d7c0cfe1
commit 6e8672bd40
9 changed files with 260 additions and 15 deletions
+5 -1
View File
@@ -229,7 +229,11 @@ namespace Swarmops.Basic.Enums
/// <summary>
/// What are activists called in this org?
/// </summary>
OrgActivistLabel
OrgActivistLabel,
/// <summary>
/// For a person, the BitId address they use to login
/// </summary>
BitIdLoginAddress
}
}
+8
View File
@@ -35,6 +35,14 @@ namespace Swarmops.Logic.Cache
return _cache[guidString].Object;
}
public static void Delete(string guidString)
{
if (_cache.ContainsKey(guidString))
{
_cache.Remove(guidString);
}
}
static private void ConditionalGarbageCollect()
{
lock (_cache) // thread safety
+17
View File
@@ -290,6 +290,23 @@ namespace Swarmops.Logic.Swarm
set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.Latitude, value); }
}
public virtual string BitIdAddress
{
get { return OptionalData.GetOptionalDataString(ObjectOptionalDataType.BitIdLoginAddress); }
set { OptionalData.SetOptionalDataString(ObjectOptionalDataType.BitIdLoginAddress, value); }
}
public static Person FromBitIdAddress(string address)
{
People candidates = People.FromOptionalData(ObjectOptionalDataType.BitIdLoginAddress, address);
if (candidates.Count == 1)
{
return candidates[0];
}
throw new ArgumentException("Zero or several candidates");
}
+3
View File
@@ -79,6 +79,9 @@ public class CommonV5Base
// Find various credentials
string identity = suppliedContext.User.Identity.Name;
// TODO: If identity is null or empty, set null user + org
string[] identityTokens = identity.Split(',');
string userIdentityString = identityTokens[0];
@@ -160,6 +160,9 @@
<value>&lt;p&gt;There is a database upgrade pending that prevents your access to this page. &lt;strong&gt;This is a temporary condition&lt;/strong&gt; and the Swarmops servers should already be working on performing the necessary upgrade.&lt;/p&gt;
&lt;p&gt;Retry loading the page in a few minutes. If the condition persists for more than fifteen minutes, contact your system administrator.&lt;/p&gt;</value>
</data>
<data name="Login_BitIdEnabled" xml:space="preserve">
<value>&lt;strong&gt;BitId two-factor authentication is now enabled.&lt;/strong&gt;&lt;br/&gt;&lt;br/&gt;From now on, you can use your bitcoin wallet to log in (and will &lt;strong&gt;need&lt;/strong&gt; to do so). Thank you for enabling added security.&lt;br/&gt;&lt;br/&gt;Please remember to keep your phone secure with a password, too.</value>
</data>
<data name="Login_GoogleAuthenticatorCode" xml:space="preserve">
<value>2FA</value>
</data>
@@ -39,9 +39,18 @@ namespace Swarmops.Frontend.Pages.v5.Security
throw new UnauthorizedAccessException();
}
string logonFlags = string.Empty;
string[] currentIdentityParts = HttpContext.Current.User.Identity.Name.Split(',');
if (currentIdentityParts.Length > 2)
{
logonFlags = currentIdentityParts[3];
}
FormsAuthentication.RedirectFromLoginPage(
CurrentUser.Identity.ToString(CultureInfo.InvariantCulture) + "," +
suggestedOrganization.Identity.ToString(CultureInfo.InvariantCulture), true); // we're not using the original input for security reasons
suggestedOrganization.Identity.ToString(CultureInfo.InvariantCulture) + ",," +
logonFlags, true);
}
}
+47 -5
View File
@@ -33,26 +33,56 @@
$(document).ready(function () {
/* document.ready goes here */
/* document.ready goes here */
setTimeout(function() {
recheckLogin();
}, 1000);
}); // end of document.ready
function recheckLogin() {
$.ajax({
type: "POST",
url: "Login.aspx/TestLogin",
data: '{"uriEncoded": "' + bitIdUri + '","nonce": "' + bitIdNonce + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if (msg.d) {
alert("Successful login! Redirecting...");
document.location = "/";
} else {
setTimeout(function () {
recheckLogin();
}, 500);
}
},
error: function (msg) {
// we don't want the polling to die just because of a transient error
setTimeout(function () {
recheckLogin();
}, 1000);
}
});
}
var bitIdUri = '<asp:Literal ID="LiteralUri" runat="server" />';
var bitIdNonce = '<asp:Literal ID="LiteralNonce" runat="server" />';
</script>
<!-- Main menu, dynamically constructed -->
<!-- Main menu, emptied out here -->
<div class="center980px">
<div class="currentuserinfo"><div style="background-image:url('/Images/Icons/iconshock-user-16px.png');background-repeat:no-repeat;padding-left:16px;float:left"><asp:Label ID="LabelCurrentUserName" runat="server" /> | </div><div style="background-image:url('/Images/Icons/iconshock-workchair-16px.png');background-repeat:no-repeat;padding-left:17px;float:left"><asp:Label ID="LabelCurrentOrganizationName" runat="server" /> |&nbsp;</div><div style="background-image:url('/Images/Icons/iconshock-gamepad-16px.png');background-repeat:no-repeat;padding-left:20px;float:left"><asp:Label ID="LabelPreferences" runat="server" /> |&nbsp;</div><asp:Image ID="ImageCultureIndicator" runat="server" ImageUrl="~/Images/Flags/uk-24px.png" /></div>
<div class="logoimage"><a href="/"><img style="border:none" src="/Security/Images/Swarmops-Logo.png" alt="Swarmops Logo" /></a></div>
<div class="break"></div>
<div class="topmenu">
<div class="searchbox"><asp:TextBox ID="SearchBox" runat="server" /></div>
<div class="searchbox"><asp:TextBox ID="SearchBox" ReadOnly="true" runat="server" /></div>
</div>
<div class="mainbar">
@@ -85,6 +115,18 @@
</div>
</div>
<asp:Panel ID="PanelCheat" runat="server">
<h2 class="blue">Dev's Cheat Button<span class="arrow"></span></h2>
<div class="box">
<div class="content" style="line-height:24px">
<p>Since we're running on localhost, on a nonstandard port, with a debugger attached, and under Windows, this is clearly not a production environment. Since it's unlikely that the outside Internet has access to this machine, which means you can't login with BitID, a cheat button has been provided for you.</p><p>Press the button below to log on as Sandbox Administrator.</p>
<asp:Button ID="ButtonCheat" runat="server" OnClick="ButtonCheat_Click" Text="Cheat Button" />
</div>
</div>
</asp:Panel>
<h2 class="orange"><asp:Label ID="LabelSidebarHelpHeader" runat="server" /><span class="arrow"></span></h2>
<div class="box">
+166 -7
View File
@@ -5,20 +5,24 @@ using System.IO;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Security;
using System.Web.Services;
using System.Web.SessionState;
using System.Web.UI;
using Swarmops.Basic.Enums;
using Swarmops.Database;
using Swarmops.Logic.Cache;
using Swarmops.Logic.Financial;
using Swarmops.Logic.Support;
using Swarmops.Logic.Swarm;
using Swarmops.Site.Automation;
using NBitcoin;
namespace Swarmops.Pages.Security
{
public partial class Login : DataV5Base // "Data" because we don't have a master page
public partial class Login : DataV5Base // "Data" because we don't have a master page
{
protected void Page_Load(object sender, EventArgs e)
{
@@ -30,13 +34,55 @@ namespace Swarmops.Pages.Security
return;
}
string jsonTest = "{\"address\":\"foobar\",\"signature\":\"flerpbar\",\"uri\":\"herpderp\"}";
BitIdCredentials credentialsTest = new JavaScriptSerializer().Deserialize<BitIdCredentials>(jsonTest);
// Check for POST data - for BitId via Webform
if (Request.HttpMethod == "POST")
{
// We should ONLY get here if we're getting a BitId by Webform submission.
if (Request.Params["address"] != null)
{
// looks like it
BitIdCredentials credentials = new BitIdCredentials
{
address = Request.Params["address"],
uri = Request.Params["uri"],
signature = Request.Params["signature"]
};
ProcessRespondBitId(credentials, Response);
return;
}
else if (Request.ContentType == "application/json")
{
BitIdCredentials credentials =
new JavaScriptSerializer().Deserialize<BitIdCredentials>(
new StreamReader(Request.InputStream).ReadToEnd());
// TODO: untested but seems to work. Throws?
ProcessRespondBitId(credentials, Response);
return;
}
}
// If this is the Dev Sandbox, autologin
if (Request.Url.Host == "dev.swarmops.com" &&
PilotInstallationIds.IsPilot(PilotInstallationIds.DevelopmentSandbox) &&
Request.QueryString["SuppressAutologin"] != "true")
{
Response.AppendCookie(new HttpCookie("DashboardMessage", HttpUtility.UrlEncode("<p>You have been logged on as <strong>Sandbox Administrator</strong> to the Swarmops Development Sandbox.</p><br/><p>This machine runs the latest development build, so you may run into diagnostic code and half-finished features. All data here is bogus test data and is reset every night.</p><br/><p><strong>In other words, welcome, and play away!</strong></p><br/><br/>")));
Response.AppendCookie(new HttpCookie("DashboardMessage",
HttpUtility.UrlEncode(
"<p>You have been logged on as <strong>Sandbox Administrator</strong> to the Swarmops Development Sandbox.</p><br/><p>This machine runs the latest development build, so you may run into diagnostic code and half-finished features. All data here is bogus test data and is reset every night.</p><br/><p><strong>In other words, welcome, and play away!</strong></p><br/><br/>")));
FormsAuthentication.RedirectFromLoginPage("1,1", true);
}
@@ -59,13 +105,17 @@ namespace Swarmops.Pages.Security
// Rewrite if applicable
if (Request.Url.ToString().StartsWith("http://") && !cloudFlareSsl) // only check client-side as many server sites de-SSL the connection before reaching the web server
if (Request.Url.ToString().StartsWith("http://") && !cloudFlareSsl)
// only check client-side as many server sites de-SSL the connection before reaching the web server
{
if (!Request.Url.ToString().StartsWith("http://dev.swarmops.com/") && !Request.Url.ToString().StartsWith("http://localhost:"))
if (!Request.Url.ToString().StartsWith("http://dev.swarmops.com/") &&
!Request.Url.ToString().StartsWith("http://localhost:"))
{
Response.Redirect(Request.Url.ToString().Replace("http:", "https:"));
}
}
}
@@ -80,10 +130,93 @@ namespace Swarmops.Pages.Security
Guid guid = Guid.NewGuid();
string guidString = guid.ToString().Replace("-", "");
// for now, fake it
string nonce = guidString + DateTime.UtcNow.Ticks.ToString("x8");
string hostName = Request.Url.Host;
string bitIdUri = "bitid://" + hostName + "/Security/Login.aspx?x=" + nonce;
if (Request.Url.ToString().StartsWith("http://") && !cloudFlareSsl)
{
bitIdUri += "&u=1";
}
this.LiteralUri.Text = HttpUtility.UrlEncode(bitIdUri);
this.LiteralNonce.Text = nonce;
GuidCache.Set(bitIdUri + "-Logon", "Unauth");
// TODO: need to NOT FUCKING USE GOOGLE CHARTS for this but bring home a QR package
this.ImageBitIdQr.ImageUrl =
"http://chart.apis.google.com/chart?cht=qr&chs=400x400&chl=bitid%3A//dev.swarmops.com/Security/Login.aspx/BitIdLogin%3Fx%3D" + guidString + "%26u%3D1";
"http://chart.apis.google.com/chart?cht=qr&chs=400x400&chl=" + HttpUtility.UrlEncode(bitIdUri);
}
protected void ProcessRespondBitId(BitIdCredentials credentials, HttpResponse response)
{
BitcoinAddress testAddress = new BitcoinAddress(credentials.address);
if (testAddress.VerifyMessage(credentials.uri, credentials.signature))
{
// woooooo
if (this.CurrentUser != null)
{
if (GuidCache.Get(credentials.uri + "-Intent") as string == "Register")
{
// set currentUser bitid
}
else if (GuidCache.Get(credentials.uri + "-Logon") as string == "Unauth")
{
Person person = Person.FromBitIdAddress(credentials.address);
// TODO: Determine last logged-on organization. Right now, log on to Sandbox.
GuidCache.Set(credentials.uri + "-LoggedOn", person.Identity.ToString(CultureInfo.InvariantCulture) + ",1,,BitId 2FA");
}
response.StatusCode = 200;
response.ContentType = "application/json";
response.Write(
new JavaScriptSerializer().Serialize(new BitIdResponseSuccess()
{
address = credentials.address,
signature = credentials.signature
}));
response.End();
}
}
else
{
// TODO: return fuckoff code (technical term)
}
}
[WebMethod]
public static bool TestLogin(string uriEncoded, string nonce)
{
string uri = HttpUtility.UrlDecode(uriEncoded);
// a little sloppy nonce and uri checking rather than full parsing
// TODO: Full parse
if (!uri.Contains(nonce) || !uri.Contains(HttpContext.Current.Request.Url.Host))
{
throw new ArgumentException();
}
string result = GuidCache.Get(uri + "-LoggedOn") as string;
if (string.IsNullOrEmpty(result))
{
return false;
}
// We have a successful login when we get here
GuidCache.Delete(uri + "-Logon");
GuidCache.Delete(uri + "-LoggedOn");
FormsAuthentication.RedirectFromLoginPage(result, true); // set auth cookie
return true;
}
protected override void OnPreInit(EventArgs e)
@@ -156,5 +289,31 @@ namespace Swarmops.Pages.Security
Response.Redirect("/", true);
}*/
}
// ReSharper disable InconsistentNaming
[Serializable]
public class BitIdCredentials
{
// Lowercase for Json serializability to BitId spec.
public string address { get; set; }
public string uri { get; set; }
public string signature { get; set; }
}
[Serializable]
public class BitIdResponseSuccess
{
// Lowercase for Json serializability to BitId spec.
public string address { get; set; }
public string signature { get; set; }
}
// ReSharper restore InconsistentNaming
protected void ButtonCheat_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
}
}