namespace Wetpaint_ToGo { public class LoginManager { private static String WetpaintTicket = "WetpaintTogoTicket"; public static String ensureLogin(String hostName, String userEmail, String userId, String userUrl, String userEmailOptIn, String userDisplayName, String developerKey, String developerSecret, String contentNamespace, String cellId) { HttpContext context = HttpContext.Current; String ticket = null; if (context.Session[WetpaintTicket] == null) { TimeSpan ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)); long unixTime = (long)ts.TotalSeconds; UTF8Encoding encoding = new UTF8Encoding(); String sigString = developerKey + userId + unixTime; HMACSHA1 hmacSha = new HMACSHA1(encoding.GetBytes(developerSecret)); byte[] sigHash = hmacSha.ComputeHash(encoding.GetBytes(sigString)); byte[] sigHash = sha.ComputeHash(encoding.GetBytes(sigString)); string encodedSigString = GetAsHexaDecimal(sigHash); string url = hostName + "/UserService/login.do"; string data = "key=" + developerKey + "&ns=" + contentNamespace + "&output=api&user.userId=" + userId + "&user.email=" + userEmail + "&user.emailOptIn=" + userEmailOptIn + "&cred.ts=" + unixTime + "&cred.sig=" + encodedSigString + "&user.profileUrl=" + userUrl + "&user.displayName=" + userDisplayName; string encodedData = HttpUtility.UrlEncode(data); Uri uri = new Uri(url); HttpWebRequest request = (HttpWebRequest)WebRequest.CreateDefault(uri); request.ContentType = "application/x-www-form-urlencoded"; request.Method = "POST"; request.ContentLength = data.Length; StreamWriter writer = new StreamWriter(request.GetRequestStream()); writer.Write(data); writer.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); string responseString = reader.ReadToEnd(); if (!responseString.Contains("<ticket>")) { //throw an exception } else { String[] tokens = {"<ticket>", "</ticket>"}; String[] splits = responseString.Split(tokens, StringSplitOptions.RemoveEmptyEntries); ticket = splits[1]; context.Session[WetpaintTicket] = ticket; } } | else { ticket = (String)context.Session[WetpaintTicket]; } return ticket; } public static void logout() { HttpContext context = HttpContext.Current; context.Session[WetpaintTicket] = null; } public static string GetAsHexaDecimal(byte[] bytes) { StringBuilder s = new StringBuilder(); int length = bytes.Length; for (int n = 0; n < length; n++) { s.Append(String.Format("{0,2:x}", bytes[n]).Replace(" ", "0")); } return s.ToString(); } } } |