public OAuthServiceCall(HttpRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            OriginalRequest  = request;
            ServiceCall      = ServiceFromString(request.PathInfo);
            ResponseCallback = util.GetStringParam(request, "callback");
            ResultFormat     = (util.GetIntParam(request, "json", 0) != 0) ? (String.IsNullOrEmpty(ResponseCallback) ? OutputFormat.JSON : OutputFormat.JSONP) : OutputFormat.XML;

            using (RSACryptoServiceProvider rsaSigning = new RSACryptoServiceProvider())
            {
                using (RSACryptoServiceProvider rsaEncryption = new RSACryptoServiceProvider())
                {
                    rsaSigning.ImportParameters(OAuth2AuthorizationServer.AuthorizationServerSigningPublicKey);
                    rsaEncryption.ImportParameters(OAuth2AuthorizationServer.CreateAuthorizationServerSigningKey());
                    ResourceServer server = new ResourceServer(new StandardAccessTokenAnalyzer(rsaSigning, rsaEncryption));
                    Token = server.GetAccessToken();

                    if (Token.Lifetime.HasValue && Token.UtcIssued.Add(Token.Lifetime.Value).CompareTo(DateTime.UtcNow) < 0)
                    {
                        throw new MyFlightbookException("oAuth2 - Token has expired!");
                    }
                    if (String.IsNullOrEmpty(Token.User))
                    {
                        throw new MyFlightbookException("Invalid oAuth token - no user");
                    }

                    GeneratedAuthToken = MFBWebService.AuthTokenFromOAuthToken(Token);
                }
            }
        }
        private void AddFlight(Stream s, MFBWebService mfbSvc)
        {
            string       szFormat = GetOptionalParam("format") ?? "Native";
            LogbookEntry le       = (szFormat.CompareCurrentCultureIgnoreCase("LTP") == 0) ?
                                    JsonConvert.DeserializeObject <LogTenPro>(GetRequiredParam("flight"), new JsonConverter[] { new MFBDateTimeConverter() }).ToLogbookEntry() :
                                    le = GetRequiredParam <LogbookEntry>("le");

            WriteObject(s, mfbSvc.CommitFlightWithOptions(GeneratedAuthToken, le, GetRequiredParam <PostingOptions>("po")));
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (String.Compare(Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase) == 0)
            {
                return;
            }

            if (!Request.IsSecureConnection)
            {
                throw new HttpException((int)HttpStatusCode.Forbidden, "Image upload MUST be on a secure channel");
            }

            if (ShuntState.IsShunted)
            {
                throw new MyFlightbookException(ShuntState.ShuntMessage);
            }

            System.Web.UI.HtmlControls.HtmlInputFile imgPicture = (System.Web.UI.HtmlControls.HtmlInputFile)FindControl("imgPicture");
            if (imgPicture == null)
            {
                throw new MyFlightbookException("No control named 'imgPicture' found!");
            }

            string szErr = "OK";

            try
            {
                string szUser = string.Empty;
                string szAuth = Request.Form["txtAuthToken"];
                if (String.IsNullOrEmpty(szAuth))
                {
                    // check for an oAuth token
                    using (OAuthServiceCall service = new OAuthServiceCall(Request))
                    {
                        szAuth = service.GeneratedAuthToken;

                        // Verify that you're allowed to modify images.
                        if (!MFBOauthServer.CheckScope(service.Token.Scope, MFBOAuthScope.images))
                        {
                            throw new UnauthorizedAccessException(String.Format(CultureInfo.CurrentCulture, "Requested action requires scope \"{0}\", which is not granted.", MFBOAuthScope.images.ToString()));
                        }
                    }
                }

                using (MFBWebService ws = new MFBWebService())
                {
                    szUser = ws.GetEncryptedUser(szAuth);
                }

                if (string.IsNullOrEmpty(szUser))
                {
                    throw new MyFlightbookException(Resources.WebService.errBadAuth);
                }

                HttpPostedFile pf = imgPicture.PostedFile;
                if (pf == null || pf.ContentLength == 0)
                {
                    throw new MyFlightbookException(Resources.WebService.errNoImageProvided);
                }

                // Upload the image, and then perform a pseudo idempotency check on it.
                MFBImageInfo mfbii = UploadForUser(szUser, pf, Request.Form["txtComment"] ?? string.Empty);
                mfbii.IdempotencyCheck();
            }
            catch (MyFlightbookException ex)
            {
                szErr = ex.Message;
            }

            Response.Clear();
            Response.ContentType = "text/plain; charset=utf-8";
            Response.Write(szErr);
        }
        /// <summary>
        /// Executes the requested service, writing any result to the specified output stream
        /// </summary>
        /// <param name="s">The output stream to which to write</param>
        public void Execute(Stream s)
        {
            string szResult = string.Empty;

            CheckAuth();

            using (MFBWebService mfbSvc = new MFBWebService())
            {
                switch (ServiceCall)
                {
                case OAuthServiceID.AddAircraftForUser:
                    WriteObject(s, mfbSvc.AddAircraftForUser(GeneratedAuthToken, GetRequiredParam("szTail"), GetRequiredParam <int>("idModel"), GetRequiredParam <int>("idInstanceType")));
                    break;

                case OAuthServiceID.AircraftForUser:
                    WriteObject(s, mfbSvc.AircraftForUser(GeneratedAuthToken));
                    break;

                case OAuthServiceID.AvailablePropertyTypesForUser:
                    WriteObject(s, mfbSvc.AvailablePropertyTypesForUser(GeneratedAuthToken));
                    break;

                case OAuthServiceID.CommitFlightWithOptions:
                case OAuthServiceID.addFlight:
                    AddFlight(s, mfbSvc);
                    break;

                case OAuthServiceID.currency:
                case OAuthServiceID.GetCurrencyForUser:
                    WriteObject(s, mfbSvc.GetCurrencyForUser(GeneratedAuthToken));
                    break;

                case OAuthServiceID.DeleteAircraftForUser:
                    WriteObject(s, mfbSvc.DeleteAircraftForUser(GeneratedAuthToken, GetRequiredParam <int>("idAircraft")));
                    break;

                case OAuthServiceID.DeleteImage:
                    mfbSvc.DeleteImage(GeneratedAuthToken, GetRequiredParam <MFBImageInfo>("mfbii"));
                    break;

                case OAuthServiceID.DeleteLogbookEntry:
                    WriteObject(s, mfbSvc.DeleteLogbookEntry(GeneratedAuthToken, GetRequiredParam <int>("idFlight")));
                    break;

                case OAuthServiceID.DeletePropertiesForFlight:
                    mfbSvc.DeletePropertiesForFlight(GeneratedAuthToken, GetRequiredParam <int>("idFlight"), GetRequiredParam <int[]>("rgPropIds"));
                    break;

                case OAuthServiceID.FlightPathForFlight:
                    WriteObject(s, mfbSvc.FlightPathForFlight(GeneratedAuthToken, GetRequiredParam <int>("idFlight")));
                    break;

                case OAuthServiceID.FlightPathForFlightGPX:
                    WriteObject(s, mfbSvc.FlightPathForFlightGPX(GeneratedAuthToken, GetRequiredParam <int>("idFlight")));
                    break;

                case OAuthServiceID.FlightsWithQueryAndOffset:
                    WriteObject(s, mfbSvc.FlightsWithQueryAndOffset(GeneratedAuthToken, GetRequiredParam <FlightQuery>("fq"), GetRequiredParam <int>("offset"), GetRequiredParam <int>("maxCount")));
                    break;

                case OAuthServiceID.MakesAndModels:
                    WriteObject(s, mfbSvc.MakesAndModels());
                    break;

                case OAuthServiceID.PropertiesForFlight:
                    WriteObject(s, mfbSvc.PropertiesForFlight(GeneratedAuthToken, GetRequiredParam <int>("idFlight")));
                    break;

                case OAuthServiceID.totals:
                case OAuthServiceID.TotalsForUserWithQuery:
                    WriteObject(s, mfbSvc.TotalsForUserWithQuery(GeneratedAuthToken, GetOptionalParam <FlightQuery>("fq")));
                    break;

                case OAuthServiceID.UpdateImageAnnotation:
                    mfbSvc.UpdateImageAnnotation(GeneratedAuthToken, GetRequiredParam <MFBImageInfo>("mfbii"));
                    break;

                case OAuthServiceID.UpdateMaintenanceForAircraftWithFlagsAndNotes:
                    mfbSvc.UpdateMaintenanceForAircraftWithFlagsAndNotes(GeneratedAuthToken, GetRequiredParam <Aircraft>("ac"));
                    break;

                case OAuthServiceID.VisitedAirports:
                    WriteObject(s, mfbSvc.VisitedAirports(GeneratedAuthToken));
                    break;

                case OAuthServiceID.GetNamedQueries:
                    WriteObject(s, mfbSvc.GetNamedQueriesForUser(GeneratedAuthToken));
                    break;

                case OAuthServiceID.AddNamedQuery:
                    WriteObject(s, mfbSvc.AddNamedQueryForUser(GeneratedAuthToken, GetRequiredParam <CannedQuery>("fq"), GetRequiredParam <string>("szName")));
                    break;

                case OAuthServiceID.DeleteNamedQuery:
                    WriteObject(s, mfbSvc.DeleteNamedQueryForUser(GeneratedAuthToken, GetRequiredParam <CannedQuery>("cq")));
                    break;

                case OAuthServiceID.none:
                case OAuthServiceID.UploadImage:        // not serviced here.
                default:
                    throw new InvalidOperationException();
                }
            }
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        Master.SelectedTab = tabID.tabUnknown;
        string szUser = String.Empty;

        if (!IsPostBack)
        {
            lblErr.Text = String.Empty;
            string szAuthToken = util.GetStringParam(Request, "auth");
            if (!String.IsNullOrEmpty(szAuthToken))
            {
                using (MFBWebService ws = new MFBWebService())
                    szUser = ws.GetEncryptedUser(szAuthToken);
            }

            bool fIsLocalOrSecure = MFBWebService.CheckSecurity(Request);

            // If no valid auth token, fall back to the authenticated name.
            if (String.IsNullOrEmpty(szUser) && Page.User.Identity.IsAuthenticated && fIsLocalOrSecure)
            {
                szUser = Page.User.Identity.Name;
            }

            // Require a secure connection for other than debugging.
            if (!fIsLocalOrSecure && !Request.IsSecureConnection)
            {
                szUser = string.Empty;
            }

            try
            {
                if (String.IsNullOrEmpty(szUser))
                {
                    throw new MyFlightbookException(Resources.SignOff.errSignNotAuthorized);
                }

                int idFlight = util.GetIntParam(Request, "idFlight", LogbookEntry.idFlightNew);
                if (idFlight == LogbookEntry.idFlightNew)
                {
                    throw new MyFlightbookException(Resources.SignOff.errSignNotAuthorized);
                }

                LogbookEntry le = new LogbookEntry();
                if (!le.FLoadFromDB(idFlight, szUser))
                {
                    throw new MyFlightbookException(Resources.SignOff.errSignNotAuthorized);
                }

                mfbSignFlight.Flight = le;
                CFIStudentMap sm = new CFIStudentMap(szUser);
                if (sm.Instructors.Count() == 0)
                {
                    mfbSignFlight.SigningMode = Controls_mfbSignFlight.SignMode.AdHoc;
                    mfbSignFlight.CFIProfile  = null;
                    mvSignFlight.SetActiveView(vwAcceptTerms);
                }
                else
                {
                    cmbInstructors.DataSource = sm.Instructors;
                    cmbInstructors.DataBind();
                    mvSignFlight.SetActiveView(vwPickInstructor);
                }


                lblHeader.Text              = String.Format(System.Globalization.CultureInfo.CurrentCulture, Resources.SignOff.SignFlightHeader, MyFlightbook.Profile.GetUser(le.User).UserFullName);
                lblDisclaimerResponse.Text  = Branding.ReBrand(Resources.SignOff.SignDisclaimerAgreement1);
                lblDisclaimerResponse2.Text = Branding.ReBrand(Resources.SignOff.SignDisclaimerAgreement2);
            }
            catch (MyFlightbookException ex)
            {
                lblErr.Text = ex.Message;
            }
        }
    }
Example #6
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string szDestErr = "~/Default.aspx";

        string szUser = util.GetStringParam(Request, "u");
        string szPass = util.GetStringParam(Request, "p");
        string szDest = util.GetStringParam(Request, "d");

        if (!MFBWebService.CheckSecurity(Request) ||
            String.IsNullOrEmpty(szUser) ||
            String.IsNullOrEmpty(szPass) ||
            String.IsNullOrEmpty(szDest))
        {
            Response.Redirect(szDestErr);
        }

        // look for admin emulation in the form of
        string[] rgUsers   = szUser.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
        string   szEmulate = string.Empty;

        if (rgUsers != null && rgUsers.Length == 2)
        {
            szEmulate = rgUsers[0];
            szUser    = rgUsers[1];
        }

        szUser = Membership.GetUserNameByEmail(szUser);

        if (Membership.ValidateUser(szUser, szPass))
        {
            if (!String.IsNullOrEmpty(szEmulate))   // emulation requested - validate that the authenticated user is actually authorized!!!
            {
                Profile pf = MyFlightbook.Profile.GetUser(szUser);
                if (pf.CanSupport || pf.CanManageData)
                {
                    // see if the emulated user actually exists
                    pf = MyFlightbook.Profile.GetUser(szEmulate);
                    if (!pf.IsValid())
                    {
                        throw new MyFlightbookException("No such user: "******"iPhone") || Request.UserAgent.Contains("iPad"))
        {
            if (String.Compare(szDest, "students", StringComparison.CurrentCultureIgnoreCase) == 0)
            {
                szDest = "instructors";
            }
            else if (String.Compare(szDest, "instructors", StringComparison.CurrentCultureIgnoreCase) == 0)
            {
                szDest = "students";
            }
        }

        szDest = RedirForDest(szDest, lstParams);

        // this is something of a hack, but pass on any additional parameters
        foreach (string szKey in Request.QueryString.Keys)
        {
            if (szKey != "u" && szKey != "p" && szKey != "d")
            {
                lstParams.Add(String.Format(CultureInfo.InvariantCulture, "{0}={1}", szKey, Request.Params[szKey]));
            }
        }

        if (lstParams.Contains("naked=1"))
        {
            Session["IsNaked"] = true;
        }

        if (szDest.Length == 0)
        {
            Response.Redirect(szDestErr);
        }
        else
        {
            string szUrlRedir = String.Format(CultureInfo.InvariantCulture, "javascript:window.top.location='{0}?{1}'", ResolveUrl(szDest), String.Join("&", lstParams.ToArray()));
            Page.ClientScript.RegisterStartupScript(this.GetType(), "StartupRedir", szUrlRedir, true);
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        Master.SelectedTab = tabID.tabUnknown;

        if (!IsPostBack)
        {
            lblErr.Text = String.Empty;
            string szAuthToken = util.GetStringParam(Request, "auth");
            if (!String.IsNullOrEmpty(szAuthToken))
            {
                Username = MFBWebService.GetEncryptedUser(szAuthToken);
            }

            bool fIsLocalOrSecure = MFBWebService.CheckSecurity(Request);

            // If no valid auth token, fall back to the authenticated name.
            if (String.IsNullOrEmpty(Username) && Page.User.Identity.IsAuthenticated && fIsLocalOrSecure)
            {
                Username = Page.User.Identity.Name;
            }

            // Require a secure connection for other than debugging.
            if (!fIsLocalOrSecure && !Request.IsSecureConnection)
            {
                Username = string.Empty;
            }

            try
            {
                if (String.IsNullOrEmpty(Username))
                {
                    throw new MyFlightbookException(Resources.SignOff.errSignNotAuthorized);
                }

                int idFlight = util.GetIntParam(Request, "idFlight", LogbookEntry.idFlightNew);
                if (idFlight == LogbookEntry.idFlightNew)
                {
                    throw new MyFlightbookException(Resources.SignOff.errSignNotAuthorized);
                }

                LogbookEntry le = new LogbookEntry();
                if (!le.FLoadFromDB(idFlight, Username))
                {
                    throw new MyFlightbookException(Resources.SignOff.errSignNotAuthorized);
                }

                mfbSignFlight.Flight = le;
                CFIStudentMap sm = new CFIStudentMap(Username);

                if (Username == null)
                {
                    throw new MyFlightbookValidationException("No username for previously signed flights");
                }

                Dictionary <string, LogbookEntry> d = PreviouslySignedAdhocFlights;

                // If no instructors, and no previously signed flights, assume ad-hoc and go straight to accept terms.
                if (!sm.Instructors.Any() && d.Keys.Count == 0)
                {
                    mfbSignFlight.SigningMode = Controls_mfbSignFlight.SignMode.AdHoc;
                    mfbSignFlight.CFIProfile  = null;
                    mvSignFlight.SetActiveView(vwAcceptTerms);
                }
                else
                {
                    rptInstructors.DataSource = sm.Instructors;
                    rptInstructors.DataBind();

                    List <string> lstKeys = new List <string>(d.Keys);
                    lstKeys.Sort();
                    List <LogbookEntry> lstPrevInstructors = new List <LogbookEntry>();

                    foreach (string sz in lstKeys)
                    {
                        lstPrevInstructors.Add(d[sz]);
                    }

                    rptPriorInstructors.DataSource = lstPrevInstructors;
                    rptPriorInstructors.DataBind();

                    mvSignFlight.SetActiveView(vwPickInstructor);
                }


                lblHeader.Text              = String.Format(CultureInfo.CurrentCulture, Resources.SignOff.SignFlightHeader, MyFlightbook.Profile.GetUser(le.User).UserFullName);
                lblDisclaimerResponse.Text  = Branding.ReBrand(Resources.SignOff.SignDisclaimerAgreement1);
                lblDisclaimerResponse2.Text = Branding.ReBrand(Resources.SignOff.SignDisclaimerAgreement2);
            }
            catch (MyFlightbookException ex)
            {
                lblErr.Text = ex.Message;
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        string szDest    = "";
        string szDestErr = "~/Default.aspx";

        string szUser = util.GetStringParam(Request, "u");
        string szPass = util.GetStringParam(Request, "p");

        szDest = util.GetStringParam(Request, "d");

        if (!MFBWebService.CheckSecurity(Request) ||
            String.IsNullOrEmpty(szUser) ||
            String.IsNullOrEmpty(szPass) ||
            String.IsNullOrEmpty(szDest))
        {
            Response.Redirect(szDestErr);
        }

        szUser = Membership.GetUserNameByEmail(szUser);

        if (Membership.ValidateUser(szUser, szPass))
        {
            FormsAuthentication.SetAuthCookie(szUser, false);
        }

        List <string> lstParams = new List <string>();

        // BUGBUG: I got students/instructors reversed in iPhone.
        if (Request.UserAgent.Contains("iPhone") || Request.UserAgent.Contains("iPad"))
        {
            if (String.Compare(szDest, "students", StringComparison.CurrentCultureIgnoreCase) == 0)
            {
                szDest = "instructors";
            }
            else if (String.Compare(szDest, "instructors", StringComparison.CurrentCultureIgnoreCase) == 0)
            {
                szDest = "students";
            }
        }

        szDest = RedirForDest(szDest, lstParams);

        // this is something of a hack, but pass on any additional parameters
        foreach (string szKey in Request.QueryString.Keys)
        {
            if (szKey != "u" && szKey != "p" && szKey != "d")
            {
                lstParams.Add(String.Format(CultureInfo.InvariantCulture, "{0}={1}", szKey, Request.Params[szKey]));
            }
        }

        if (lstParams.Contains("naked=1"))
        {
            Session["IsNaked"] = true;
        }

        if (szDest.Length == 0)
        {
            Response.Redirect(szDestErr);
        }
        else
        {
            string szUrlRedir = String.Format(CultureInfo.InvariantCulture, "javascript:window.top.location='{0}?{1}'", ResolveUrl(szDest), String.Join("&", lstParams.ToArray()));
            Page.ClientScript.RegisterStartupScript(this.GetType(), "StartupRedir", szUrlRedir, true);
        }
    }