Exemplo n.º 1
0
        public void StartSession(OAuthToken token)
        {
            core.Session = new SessionState(core, db, token, httpContext.Request, httpContext.Response);

            if (core.Session.LoggedInMember != null)
            {
                tz = core.Session.LoggedInMember.UserInfo.GetTimeZone;
            }

            // move it here
            core.Tz = tz;
        }
Exemplo n.º 2
0
        private void RequestOAuthAccessToken()
        {
            // Final step in oauth handshake

            OAuthApplication oae = null;
            string nonce = null;

            string verifier = core.Http.Form["oauth_verifier"];

            OAuthVerifier oAuthVerifier = null;
            OAuthToken oauthToken = null;

            try
            {
                oAuthVerifier = new OAuthVerifier(core, verifier);
            }
            catch (InvalidOAuthVerifierException)
            {
                core.Http.StatusCode = 401;

                NameValueCollection response = new NameValueCollection();
                response.Add("error", "unauthorised, invalid verifier");

                core.Http.WriteAndEndResponse(response);
                return;
            }

            if (oAuthVerifier.Expired)
            {
                core.Http.StatusCode = 401;

                NameValueCollection response = new NameValueCollection();
                response.Add("error", "unauthorised, verifier expired");

                core.Http.WriteAndEndResponse(response);
                return;
            }

            try
            {
                oauthToken = new OAuthToken(core, oAuthVerifier.TokenId);
            }
            catch (InvalidOAuthTokenException)
            {
                core.Http.StatusCode = 401;

                NameValueCollection response = new NameValueCollection();
                response.Add("error", "unauthorised, invalid token");

                core.Http.WriteAndEndResponse(response);
                return;
            }

            if (AuthoriseRequest("/oauth/access_token", oauthToken, out oae, out nonce))
            {
                oAuthVerifier.UseVerifier();

                // TODO: check application is not already installed
                SelectQuery query = new SelectQuery(typeof(PrimitiveApplicationInfo));
                query.AddCondition("application_id", oauthToken.ApplicationId);
                query.AddCondition("item_id", oAuthVerifier.UserId);
                query.AddCondition("item_type_id", ItemKey.GetTypeId(core, typeof(User)));

                System.Data.Common.DbDataReader appReader = db.ReaderQuery(query);

                if (!appReader.HasRows)
                {
                    appReader.Close();
                    appReader.Dispose();

                    OAuthToken oauthAuthToken = OAuthToken.Create(core, oae, nonce);

                    InsertQuery iQuery = new InsertQuery("primitive_apps");
                    iQuery.AddField("application_id", oauthToken.ApplicationId);
                    iQuery.AddField("item_id", oAuthVerifier.UserId);
                    iQuery.AddField("item_type_id", ItemKey.GetTypeId(core, typeof(User)));
                    iQuery.AddField("app_email_notifications", true);
                    iQuery.AddField("app_oauth_access_token", oauthAuthToken.Token);
                    iQuery.AddField("app_oauth_access_token_secret", oauthAuthToken.TokenSecret);

                    if (core.Db.Query(iQuery) > 0)
                    {
                        // successfull
                    }

                    db.CommitTransaction();

                    NameValueCollection response = new NameValueCollection();
                    response.Add("oauth_token", oauthAuthToken.Token);
                    response.Add("oauth_token_secret", oauthAuthToken.TokenSecret);

                    core.Http.WriteAndEndResponse(response);
                }
                else
                {
                    appReader.Read();

                    PrimitiveApplicationInfo pai = new PrimitiveApplicationInfo(core, appReader);

                    appReader.Close();
                    appReader.Dispose();

                    NameValueCollection response = new NameValueCollection();
                    response.Add("oauth_token", pai.OAuthAccessToken);
                    response.Add("oauth_token_secret", pai.OAuthAccessTokenSecret);

                    core.Http.WriteAndEndResponse(response);
                }
            }
            else
            {
                // FAIL
                core.Http.StatusCode = 401;

                NameValueCollection response = new NameValueCollection();
                response.Add("error", "unauthorised, access token rejected");

                core.Http.WriteAndEndResponse(response);
                core.Http.End();
                return;
            }
        }
Exemplo n.º 3
0
        private bool AuthoriseRequest(string path, OAuthToken token, out OAuthApplication oae, out string nonce)
        {
            string authorisationHeader = ReadAuthorisationHeader();

            if (authorisationHeader != null && authorisationHeader.StartsWith("OAuth "))
            {
                NameValueCollection authorisationHeaders = ParseAuthorisationHeader(authorisationHeader.Substring(6));

                string requestConsumerKey = authorisationHeaders["oauth_consumer_key"];

                try
                {
                    oae = new OAuthApplication(core, requestConsumerKey);
                    nonce = authorisationHeaders["oauth_nonce"];

                    SortedDictionary<string, string> signatureParamaters = new SortedDictionary<string, string>();

                    foreach (string key in authorisationHeaders.Keys)
                    {
                        if (key == null)
                        {
                        }
                        else if (key == "oauth_signature")
                        {
                        }
                        else
                        {
                            signatureParamaters.Add(key, authorisationHeaders[key]);
                        }
                    }

                    foreach (string key in core.Http.Query.Keys)
                    {
                        if (string.IsNullOrEmpty(key))
                        {
                        }
                        else if (key.StartsWith("global_"))
                        {
                        }
                        else if (key == "oauth_signature")
                        {
                        }
                        else
                        {
                            signatureParamaters.Add(key, core.Http.Query[key]);
                        }
                    }

                    foreach (string key in core.Http.Form.Keys)
                    {
                        //if (key == "oauth_verifier")
                        if (string.IsNullOrEmpty(key))
                        {
                        }
                        else
                        {
                            signatureParamaters.Add(key, core.Http.Form[key]);
                        }
                    }

                    string parameters = string.Empty;

                    foreach (string key in signatureParamaters.Keys)
                    {
                        if (parameters != string.Empty)
                        {
                            parameters += "&";
                        }
                        parameters += string.Format("{0}={1}", OAuth.UrlEncode(key), OAuth.UrlEncode(signatureParamaters[key]));
                    }

                    string signature = core.Http.HttpMethod + "&" + OAuth.UrlEncode(core.Http.Host + path) + "&" + OAuth.UrlEncode(parameters);

                    if (token == null)
                    {
                        string oauthToken = authorisationHeaders["oauth_token"];

                        if (!string.IsNullOrEmpty(oauthToken))
                        {
                            try
                            {
                                token = new OAuthToken(core, oauthToken);

                                // start session
                                StartSession(token);
                            }
                            catch (InvalidOAuthTokenException)
                            {
                                oae = null;
                                nonce = null;
                                return false;
                            }
                        }
                    }

                    string requestSignature = authorisationHeaders["oauth_signature"];
                    string expectedSignature = OAuth.ComputeSignature(signature, oae.ApiSecret + "&" + (token != null ? token.TokenSecret : string.Empty));

                    if (requestSignature == expectedSignature)
                    {
                        return true;
                    }
            #if DEBUG
                    else
                    {
                        HttpContext.Current.Response.Write("Request signature: " + requestSignature + "\r\n");
                        HttpContext.Current.Response.Write("Expected signature: " + expectedSignature + "\r\n");
                        HttpContext.Current.Response.Write("signature: " + signature + "\r\n");
                        if (token != null)
                        {
                            HttpContext.Current.Response.Write("token: " + token.Token + "\r\n");
                            HttpContext.Current.Response.Write("secret: " + token.TokenSecret + "\r\n");
                        }
                    }
            #endif
                }
                catch (InvalidApplicationException)
                {
                    oae = null;
                    nonce = null;
                    return false;
                }
            }

            oae = null;
            nonce = null;
            return false;
        }
Exemplo n.º 4
0
        public SessionState(Core core, Mysql db, OAuthToken token, HttpRequest Request, HttpResponse Response)
        {
            if (core == null)
            {
                throw new NullCoreException();
            }

            this.Request = Request;
            this.Response = Response;
            this.db = db;
            this.core = core;

            applicationId = token.ApplicationId;

            SelectQuery query = new SelectQuery(typeof(PrimitiveApplicationInfo));
            query.AddCondition("application_id", token.ApplicationId);
            query.AddCondition("app_oauth_access_token", token.Token);

            System.Data.Common.DbDataReader appReader = core.Db.ReaderQuery(query);

            if (appReader.HasRows)
            {
                appReader.Read();
                PrimitiveApplicationInfo pai = new PrimitiveApplicationInfo(core, appReader);

                appReader.Close();
                appReader.Dispose();

                if (pai.Owner is User)
                {
                    this.core = core;
                    this.db = core.Db;
                    isLoggedIn = true;
                    this.signInState = SessionSignInState.SignedIn;
                    loggedInMember = (User)pai.Owner;
                    ipAddress = IPAddress.Parse(SessionState.ReturnRealIPAddress(Request.ServerVariables));
                    this.sessionMethod = SessionMethods.OAuth;
                }
            }
            else
            {
                appReader.Close();
                appReader.Dispose();

                this.core = core;
                this.db = core.Db;
                isLoggedIn = false;
                this.signInState = SessionSignInState.SignedOut;
                ipAddress = IPAddress.Parse(SessionState.ReturnRealIPAddress(Request.ServerVariables));
                this.sessionMethod = SessionMethods.OAuth;
            }
        }
Exemplo n.º 5
0
        public static OAuthVerifier Create(Core core, OAuthToken token, User user)
        {
            string newVerifier = string.Empty;

            do
            {
                newVerifier = OAuth.GeneratePublic();
            } while (!CheckVerifierUnique(core, newVerifier));

            Item item = Item.Create(core, typeof(OAuthVerifier), new FieldValuePair("oauth_token_id", token.Id),
                new FieldValuePair("oauth_verifier", newVerifier),
                new FieldValuePair("oauth_verifier_user_id", user.Id),
                new FieldValuePair("oauth_verifier_expired", false));

            OAuthVerifier newOAuthVerifier = (OAuthVerifier)item;

            return newOAuthVerifier;
        }
Exemplo n.º 6
0
        private void OAuthAuthorize(bool fail)
        {
            bool forceLogin = (core.Http.Query["force_login"] == "true");
            string oauthToken = core.Http["oauth_token"];

            try
            {
                OAuthToken token = new OAuthToken(core, oauthToken);
                ApplicationEntry ae = token.Application;

                TextBox usernameTextBox = new TextBox("username");
                TextBox passwordTextBox = new TextBox("password", InputType.Password);

                HiddenField oauthTokenHiddenField = new HiddenField("oauth_token");
                oauthTokenHiddenField.Value = oauthToken;

                SubmitButton submitButton = new SubmitButton("submit", core.Prose.GetString("AUTHORISE"));
                Button cancelButton = new Button("cancel", core.Prose.GetString("CANCEL"), "cancel");
                cancelButton.Script.OnClick = "window.external.notify('cancel'); return false;";

                if (token.TokenExpired)
                {
                    core.Functions.Generate403();
                    EndResponse();
                    return;
                }

                template.SetTemplate("oauth_authorize.html");

                template.Parse("U_POST", core.Hyperlink.AppendSid("/oauth/approve", true));
                template.Parse("REQUIRE_LOGIN", ((forceLogin || (!core.Session.SignedIn)) ? "TRUE" : "FALSE"));
                template.Parse("AUTHORISE_APPLICATION", string.Format(core.Prose.GetString("AUTHORISE_APPLICATION"), ae.Title));
                template.Parse("APPLICATION_ICON", ae.Icon);
                template.Parse("S_USERNAME", usernameTextBox);
                template.Parse("S_PASSWORD", passwordTextBox);
                template.Parse("S_OAUTH_TOKEN", oauthTokenHiddenField);
                template.Parse("S_SUBMIT", submitButton);
                template.Parse("S_CANCEL", cancelButton);
            }
            catch (InvalidOAuthTokenException)
            {
                core.Functions.Generate403();
            }
            catch (InvalidApplicationException)
            {
                core.Functions.Generate403();
            }

            EndResponse();
        }
Exemplo n.º 7
0
        private void OAuthApprove()
        {
            string oauthToken = core.Http.Form["oauth_token"];
            bool success = false;

            try
            {
                OAuthToken token = new OAuthToken(core, oauthToken);
                ApplicationEntry ae = token.Application;
                OAuthApplication oae = new OAuthApplication(core, ae);

                if (core.Http.Form["mode"] == "verify")
                {
                    Authenticator authenticator = new Authenticator();

                    if (authenticator.CheckCode(core.Session.CandidateMember.UserInfo.TwoFactorAuthKey, core.Http.Form["verify"]))
                    {
                        success = true;
                    }
                    else
                    {
                        showVerificationForm(ae, oauthToken, core.Session.SessionId);

                        return;
                    }
                }
                else
                {

                    bool authenticated = false;

                    string userName = Request.Form["username"];
                    string password = BoxSocial.Internals.User.HashPassword(Request.Form["password"]);

                    DataTable userTable = db.Query(string.Format("SELECT uk.user_name, uk.user_id, ui.user_password, ui.user_two_factor_auth_key, ui.user_two_factor_auth_verified FROM user_keys uk INNER JOIN user_info ui ON uk.user_id = ui.user_id WHERE uk.user_name = '{0}';",
                       userName));

                    if (userTable.Rows.Count == 1)
                    {
                        DataRow userRow = userTable.Rows[0];
                        string dbPassword = (string)userRow["user_password"];

                        if (dbPassword == password)
                        {
                            authenticated = true;
                        }

                        if (authenticated)
                        {
                            if ((byte)userRow["user_two_factor_auth_verified"] > 0)
                            {
                                string sessionId = session.SessionBegin((long)userRow["user_id"], false, false, false);

                                showVerificationForm(ae, oauthToken, sessionId);

                                return;
                            }
                            else
                            {
                                string sessionId = session.SessionBegin((long)userRow["user_id"], false, false);

                                success = true;
                            }
                        }
                        else
                        {
                            OAuthAuthorize(true);
                            return;
                        }
                    }
                }

                if (success)
                {
                    OAuthVerifier verifier = OAuthVerifier.Create(core, token, core.Session.CandidateMember);
                    token.UseToken();

                    db.CommitTransaction();

                    if (!string.IsNullOrEmpty(oae.CallbackUrl))
                    {
                        Response.Redirect(string.Format("{0}?oauth_token={1}&oauth_verifier={2}", oae.CallbackUrl, Uri.EscapeDataString(token.Token), Uri.EscapeDataString(verifier.Verifier)));
                    }
                    else
                    {
                        core.Response.SendRawText("", string.Format("oauth_token={0}&oauth_verifier={1}", Uri.EscapeDataString(token.Token), Uri.EscapeDataString(verifier.Verifier)));
                    }
                }
                else
                {
                    // Incorrect password
                    OAuthAuthorize(true);
                    return;
                }
            }
            catch (InvalidOAuthTokenException)
            {
                core.Functions.Generate403();
            }

            EndResponse();
        }
Exemplo n.º 8
0
        public bool Deauthorise(Core core, Primitive viewer, Primitive owner)
        {
            if (this.ApplicationType != Internals.ApplicationType.OAuth) return false;

            try
            {
                PrimitiveApplicationInfo pai = new PrimitiveApplicationInfo(core, owner, this.Id);

                OAuthToken token = new OAuthToken(core, pai.OAuthAccessToken);
                token.UseToken();
                token.Update();

                DeleteQuery dQuery = new DeleteQuery(typeof(PrimitiveApplicationInfo));
                dQuery.AddCondition("application_id", Id);
                dQuery.AddCondition("item_id", owner.Id);
                dQuery.AddCondition("item_type_id", owner.TypeId);

                if (core.Db.Query(dQuery) > 0)
                {
                    return true;
                }
            }
            catch (InvalidPrimitiveAppInfoException)
            {
            }
            catch (InvalidOAuthTokenException)
            {
            }

            return false;
        }