Ejemplo n.º 1
0
 /// <summary>
 ///     匹配EOF
 /// </summary>
 /// <param name="facade">占位符</param>
 /// <param name="expr">表达式</param>
 // ReSharper disable once UnusedParameter.Global
 public static void Eof(this FacadeBase facade, string expr)
 {
     if (!string.IsNullOrWhiteSpace(expr))
     {
         throw new ArgumentException("语法错误", nameof(expr));
     }
 }
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            //Checks whether user information has been entered
            if (actionContext.Request.Headers.Authorization == null)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden,
                                                                              "You must send user name and password in basic authentication");
                return;
            }

            //Encoding the user name and password from base64
            string authenticationToken        = actionContext.Request.Headers.Authorization.Parameter;
            string decodedAuthenticationToken = Encoding.UTF8.GetString(
                Convert.FromBase64String(authenticationToken));

            string[] usernamePasswordArray = decodedAuthenticationToken.Split(':');
            string   username = usernamePasswordArray[0];
            string   password = usernamePasswordArray[1];

            if (username == "admin" && password == "9999")
            {
                FacadeBase fb = FlyingCenterSystem.GetInstance().Login(username, password, out LoginTokenBase token);
                actionContext.Request.Properties["administratorToken"] = token;
                LoggedInAdministratorFacade administratorFacade = (LoggedInAdministratorFacade)fb;
                actionContext.Request.Properties["administratorFacade"] = administratorFacade;
            }
            else
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                                              "You are not authorized");
            }
        }
Ejemplo n.º 3
0
        public LoggedInAirlineFacade getCompanyLoginToken()
        {
            Request.Properties.TryGetValue("airlineCompany-login-token", out object loginUser);
            companyToken = (LoginToken <AirlineCompany>)loginUser;
            FacadeBase LoginIFacade = FlyingCenterSystem.GetInstance().GetFacade(companyToken);

            return((LoggedInAirlineFacade)LoginIFacade);
        }
Ejemplo n.º 4
0
        public LoggedInCustomerFacade getCustomerFacade()
        {
            Request.Properties.TryGetValue("login-customer", out object loginUser);
            customerLoginToken = (LoginToken <Customer>)loginUser;
            FacadeBase LoginIFacade = FlyingCenterSystem.GetInstance().GetFacade(customerLoginToken);

            return((LoggedInCustomerFacade)LoginIFacade);
        }
Ejemplo n.º 5
0
        public LoggedInAdministratorFacade getAdminLoginToken()
        {
            Request.Properties.TryGetValue("login-token", out object loginUser);
            adminLoginToken = (LoginToken <Administrator>)loginUser;
            FacadeBase LoginIFacade = FlyingCenterSystem.GetInstance().GetFacade(adminLoginToken);

            return((LoggedInAdministratorFacade)LoginIFacade);
        }
Ejemplo n.º 6
0
        public BetListViewModel(ISubject subject, FacadeBase <BetDisplayModel> facade)
        {
            this.facade = facade;

            this.EditBetCommand = new DelegateCommand(() => RaiseBetSelectedEvent(SelectedBet), obj => SelectedBet != null);

            this.Bets = new ObservableCollection <BetDisplayModel>(facade.GetAll());

            subject.Subscribe(this);
        }
Ejemplo n.º 7
0
 public void BindFactoryTestCase()
 {
     GivenCreateFactory()
     .When("create facade", _ => FacadeBase.Create <Facade>(Factory))
     .Then("Check result", facade =>
     {
         facade.AssertFactory(Factory);
     })
     .Run();
 }
Ejemplo n.º 8
0
 public void CreateFacadeTestCase()
 {
     GivenCreateFactory()
     .When("create facade", _ => FacadeBase.Create <Facade>(Factory))
     .Then("Check result", facade =>
     {
         Assert.IsNotNull(facade, "facade cannot be null");
     })
     .Run();
 }
Ejemplo n.º 9
0
        public SportListViewModel(ISubject subject, FacadeBase <string> facade)
        {
            this.subject = subject;
            this.facade  = facade;

            this.Sports             = new ObservableCollection <string>(facade.GetAll());
            this.EditSportCommand   = new DelegateCommand(() => RaiseSportSelectedEvent(SelectedSport), obj => SelectedSport != null);
            this.DeleteSportCommand = new DelegateCommand(() => RaiseSportDeleteRequestEvent(SelectedSport), obj => SelectedSport != null);

            subject.Subscribe(this);
        }
Ejemplo n.º 10
0
        public ManageClientsViewModel(ISubject subject, FacadeBase <ClientDisplayModel> facade)
        {
            ClientListViewModel = new ClientListViewModel(subject, facade);

            this.SelectClientCommand = new DelegateCommand(
                () => RaiseClientSelectRequestEvent(SelectedClient),
                obj => SelectedClient != null);
            this.DeleteClientCommand = new DelegateCommand(
                () => RaiseClientDeleteRequestEvent(SelectedClient),
                obj => SelectedClient != null);
        }
Ejemplo n.º 11
0
        public CountryListViewModel(ISubject subject, FacadeBase <string> facade)
        {
            this.subject = subject;
            this.facade  = facade;

            this.Countries            = new ObservableCollection <string>(facade.GetAll());
            this.EditCountryCommand   = new DelegateCommand(() => RaiseCountrySelectedEvent(SelectedCountry), obj => SelectedCountry != null);
            this.DeleteCountryCommand = new DelegateCommand(() => RaiseCountryDeleteRequestEvent(SelectedCountry), obj => SelectedCountry != null);

            subject.Subscribe(this);
        }
Ejemplo n.º 12
0
        /// <summary>
        ///     匹配可选的非零长度字符串
        /// </summary>
        /// <param name="facade">占位符</param>
        /// <param name="expr">表达式</param>
        /// <param name="opt">字符串</param>
        /// <returns>是否匹配</returns>
        // ReSharper disable once UnusedParameter.Global
        public static bool Optional(this FacadeBase facade, ref string expr, string opt)
        {
            expr = expr.TrimStart();
            if (!expr.StartsWith(opt, StringComparison.Ordinal))
            {
                return(false);
            }

            expr = expr.Substring(opt.Length);
            return(true);
        }
        public ManageBookmakersViewModel(ISubject subject, FacadeBase <BookmakerDisplayModel> facade)
        {
            BookmakerListViewModel = new BookmakerListViewModel(subject, facade);

            this.SelectBookmakerCommand = new DelegateCommand(
                () => RaiseBookmakerSelectRequestEvent(SelectedBookmaker),
                obj => SelectedBookmaker != null);
            this.DeleteBookmakerCommand = new DelegateCommand(
                () => RaiseBookmakerDeleteRequestEvent(SelectedBookmaker),
                obj => SelectedBookmaker != null);
        }
Ejemplo n.º 14
0
        /// <summary>
        ///     匹配可选的数
        /// </summary>
        /// <param name="facade">占位符</param>
        /// <param name="expr">表达式</param>
        /// <returns>数</returns>
        public static double?Double(this FacadeBase facade, ref string expr)
        {
            var d = double.NaN;

            if (facade.Token(ref expr, false, t => double.TryParse(t, out d)) != null)
            {
                return(d);
            }

            return(null);
        }
Ejemplo n.º 15
0
        public BookmakerListViewModel(ISubject subject, FacadeBase <BookmakerDisplayModel> facade)
        {
            this.subject = subject;
            this.facade  = facade;

            subject.Subscribe(this);

            this.Bookmakers = new ObservableCollection <BookmakerDisplayModel>(facade.GetAll());
            this.SortedBookmakers.Filter = FilterBookmaker;
            this.RefreshBookmakers       = new DelegateCommand(() => SortedBookmakers.Refresh(), obj => true);

            RaisePropertyChangedEvent("Bookmakers");
            RaisePropertyChangedEvent("SelectedBookmaker");
        }
Ejemplo n.º 16
0
        public ClientListViewModel(ISubject subject, FacadeBase <ClientDisplayModel> facade)
        {
            this.subject = subject;
            this.facade  = facade;

            subject.Subscribe(this);

            this.Clients = new ObservableCollection <ClientDisplayModel>(facade.GetAll());
            this.SortedClients.Filter = FilterClient;
            this.RefreshClients       = new DelegateCommand(() => SortedClients.Refresh(), obj => true);

            RaisePropertyChangedEvent("Clients");
            RaisePropertyChangedEvent("SelectedClient");
        }
Ejemplo n.º 17
0
        public EventListViewModel(ISubject subject, FacadeBase <EventDisplayModel> facade)
        {
            this.facade = facade;

            this.SelectEventCommand = new DelegateCommand(
                () => RaiseEventSelectedEvent(SelectedEvent),
                obj => SelectedEvent != null);
            this.DeleteEventCommand = new DelegateCommand(
                () => RaiseEventDeleteRequestEvent(SelectedEvent),
                obj => SelectedEvent != null);

            this.Events = new ObservableCollection <EventDisplayModel>(facade.GetAll());

            subject.Subscribe(this);
        }
Ejemplo n.º 18
0
        static void Main(string[] args)
        {
            FacadeBase FB = new FacadeBase();

            Ticket tk  = new Ticket(5, 2, 1);
            Ticket tk2 = new Ticket(5, 1, 1);

            Console.WriteLine("getting all tickets:");
            List <Ticket> tickets = FB.GetAllTickets();

            tickets.ForEach(t => Console.WriteLine(t));
            Console.WriteLine("");

            Console.WriteLine("adding ticket with id - 5, flight id - 2, customer id - 1");
            FB.AddTicket(tk);
            Console.WriteLine("");

            Console.WriteLine("Getting ticket with id of 5:");
            Console.WriteLine(FB.GetTicket(5));
            Console.WriteLine("");

            Console.WriteLine("getting all tickets:");
            tickets = FB.GetAllTickets();
            tickets.ForEach(t => Console.WriteLine(t));
            Console.WriteLine("");

            Console.WriteLine("updating ticket with id - 5, flight id - 2 => 1");
            FB.UpdateTicket(tk2);
            Console.WriteLine("");

            Console.WriteLine("Getting ticket with id of 5:");
            Console.WriteLine(FB.GetTicket(5));
            Console.WriteLine("");

            Console.WriteLine("getting all tickets:");
            tickets = FB.GetAllTickets();
            tickets.ForEach(t => Console.WriteLine(t));
            Console.WriteLine("");

            Console.WriteLine("removing ticket with id - 5:");
            FB.RemoveTicket(tk2);
            Console.WriteLine("");

            Console.WriteLine("getting all tickets:");
            tickets = FB.GetAllTickets();
            tickets.ForEach(t => Console.WriteLine(t));
            Console.WriteLine("");
        }
Ejemplo n.º 19
0
        /// <summary>
        ///     匹配带括号和连续字符串
        /// </summary>
        /// <param name="facade">占位符</param>
        /// <param name="expr">表达式</param>
        /// <param name="allow">允许括号</param>
        /// <param name="predicate">是否有效</param>
        /// <returns>字符串</returns>
        public static string Token(this FacadeBase facade, ref string expr, bool allow = true,
                                   Func <string, bool> predicate = null)
        {
            expr = expr.TrimStart();
            if (expr.Length == 0)
            {
                return(null);
            }

            if (allow)
            {
                if (expr[0] == '\'' ||
                    expr[0] == '"')
                {
                    var tmp = expr;
                    var res = facade.Quoted(ref expr);
                    if (!predicate?.Invoke(res) != true)
                    {
                        return(res);
                    }

                    expr = tmp;
                    return(null);
                }
            }

            var id = 1;

            while (id < expr.Length)
            {
                if (char.IsWhiteSpace(expr[id]))
                {
                    break;
                }

                id++;
            }

            var t = expr.Substring(0, id);

            if (!predicate?.Invoke(t) == true)
            {
                return(null);
            }

            expr = expr.Substring(id);
            return(t);
        }
Ejemplo n.º 20
0
        /// <summary>
        ///     匹配行
        /// </summary>
        /// <param name="facade">占位符</param>
        /// <param name="expr">表达式</param>
        /// <returns>字符串</returns>
        public static string Line(this FacadeBase facade, ref string expr)
        {
            var id = expr.IndexOf('\n');

            if (id < 0)
            {
                var tmp = expr;
                expr = null;
                return(tmp);
            }

            var line = expr.Substring(0, id);

            expr = expr.Substring(id + 1);
            return(line);
        }
Ejemplo n.º 21
0
        //Type,Dll|Method此类格式
        //参数用|分隔
        public void ProcessRequest(HttpContext context)
        {
            string strReturn = "";

            try
            {
                var para = HttpUtility.UrlDecode(context.Request.Form.ToString()).ToJsonObject();
                if (para == null)
                {
                    throw new Exception("请求参数无效,请核对参数");
                }
                lock (instance.dicConstructor)
                {
                    if (!instance.dicConstructor.ContainsKey(strType + strDll))
                    {
                        Type tp = Assembly.LoadFile(System.AppDomain.CurrentDomain.BaseDirectory
                                                    + "bin\\" + strDll + ".dll").GetType(strType);
                        instance.dicConstructor.Add(strType + strDll, tp.GetConstructor(new Type[] { }));
                    }
                }
                lock (instance.dicMethod)
                {
                    if (!instance.dicMethod.ContainsKey(strType + strDll + strMethod))
                    {
                        Type tp = Assembly.LoadFile(System.AppDomain.CurrentDomain.BaseDirectory
                                                    + "bin\\" + strDll + ".dll").GetType(strType);
                        instance.dicMethod.Add(strType + strDll + strMethod, tp.GetMethod(strMethod));
                    }
                    ;
                }
                FacadeBase facade = instance.dicConstructor[strType + strDll].Invoke(null) as FacadeBase;
                facade.Context = context;
                strReturn      = instance.dicMethod[strType + strDll + strMethod]
                                 .Invoke(facade, context.Request["invokeParam"].Split('|')).ToString();
            }
            catch (Exception ex)
            {
                ErrorLog.WriteLog(ex);
                strReturn = new
                {
                    errcode = "-1",
                    errmsg  = "操作出现异常,请联系管理员"
                }.ToJsonString();
            }
            context.Response.Write(strReturn);
            context.Response.End();
        }
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (actionContext.Request.Headers.Authorization == null)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                                              "You must enter user name + password");
            }
            else
            {
                string authenticationToken = actionContext.Request.Headers.Authorization.Parameter;

                string decodedAuthenticationToken = Encoding.UTF8.GetString(
                    Convert.FromBase64String(authenticationToken));

                string[] usernamePasswordArray = decodedAuthenticationToken.Split(':');
                string   username = usernamePasswordArray[0];
                string   password = usernamePasswordArray[1];

                FlyingCenterSystem fcs        = FlyingCenterSystem.GetInstance();
                ILoginToken        loginToken = fcs.Login(username, password);
                FacadeBase         facade     = fcs.GetFacade(loginToken);
                if (loginToken.GetType() == typeof(LoginToken <Administrator>))
                {
                    // LoginToken<Administrator> token = (LoginToken<Administrator>)loginToken;
                    // LoggedInAdministratorFacade LogFacade = (LoggedInAdministratorFacade)facade;
                    actionContext.Request.Properties["AdminUser"]   = loginToken;
                    actionContext.Request.Properties["AdminFacade"] = facade;
                }
                else if (loginToken.GetType() == typeof(LoginToken <AirlineCompany>))
                {
                    actionContext.Request.Properties["AirlineUser"]   = loginToken;
                    actionContext.Request.Properties["AirlineFacade"] = facade;
                }
                else if (loginToken.GetType() == typeof(LoginToken <Customer>))
                {
                    actionContext.Request.Properties["CustomerUser"]   = loginToken;
                    actionContext.Request.Properties["CustomerFacade"] = facade;
                }

                else
                {
                    actionContext.Response = actionContext.Request
                                             .CreateResponse(HttpStatusCode.Unauthorized, "You are not allowed");
                }
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        ///     忽略空白和注释
        /// </summary>
        /// <param name="facade">占位符</param>
        /// <param name="expr">表达式</param>
        public static void TrimStartComment(this FacadeBase facade, ref string expr)
        {
            expr = expr.TrimStart();
            var regex = new Regex(@"[^\r\n]*(\r\n|\n|\n\r)");

            while (expr.Length > 2 &&
                   expr[0] == '/' &&
                   expr[1] == '/')
            {
                var m = regex.Match(expr);
                if (!m.Success)
                {
                    expr = string.Empty;
                    return;
                }

                expr = expr[m.Length..];
        private static void CopyPropertiesFromStorage <T>(T baseConfiguration, FacadeBase storage) where T : PolicyConfigurationBase
        {
            baseConfiguration.Name           = (string)storage.InnerPropertyBag[ADObjectSchema.Name];
            baseConfiguration.Workload       = (Workload)storage.InnerPropertyBag[UnifiedPolicyStorageBaseSchema.WorkloadProp];
            baseConfiguration.WhenCreatedUTC = (DateTime?)storage.InnerPropertyBag[ADObjectSchema.WhenCreatedUTC];
            baseConfiguration.WhenChangedUTC = (DateTime?)storage.InnerPropertyBag[ADObjectSchema.WhenChangedUTC];
            baseConfiguration.ChangeType     = ((storage.InnerConfigurable.ObjectState == ObjectState.Deleted) ? ChangeType.Delete : ChangeType.Update);
            baseConfiguration.Version        = PolicyVersion.Create((Guid)storage.InnerPropertyBag[UnifiedPolicyStorageBaseSchema.PolicyVersion]);
            IEnumerable <PropertyInfo> reflectedProperties = UnifiedPolicyStorageFactory.GetReflectedProperties <T>();

            UnifiedPolicyStorageFactory.InitializeIncrementalAttributes(baseConfiguration, reflectedProperties);
            IEnumerable <PropertyDefinition> propertyDefinitions = DalHelper.GetPropertyDefinitions(storage, false);

            using (IEnumerator <PropertyDefinition> enumerator = propertyDefinitions.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    PropertyDefinition property = enumerator.Current;
                    object             propertyValue;
                    if (UnifiedPolicyStorageFactory.TryReadPropertyValue(storage, property, out propertyValue))
                    {
                        PropertyInfo propertyInfo = reflectedProperties.FirstOrDefault((PropertyInfo p) => UnifiedPolicyStorageFactory.PropertiesMatch(property, p));
                        if (!(propertyInfo == null) && !UnifiedPolicyStorageFactory.IsIncrementalCollection(propertyInfo))
                        {
                            UnifiedPolicyStorageFactory.CopyPropertyFromStorage(propertyInfo, propertyValue, baseConfiguration);
                        }
                    }
                }
            }
            using (IEnumerator <PropertyInfo> enumerator2 = (from p in reflectedProperties
                                                             where UnifiedPolicyStorageFactory.IsIncrementalCollection(p)
                                                             select p).GetEnumerator())
            {
                while (enumerator2.MoveNext())
                {
                    UnifiedPolicyStorageFactory.< > c__DisplayClassf <T> CS$ < > 8__locals2 = new UnifiedPolicyStorageFactory.< > c__DisplayClassf <T>();
                    CS$ < > 8__locals2.incrementalCollectionProp = enumerator2.Current;
                    PropertyDefinition addedProperty      = propertyDefinitions.FirstOrDefault((PropertyDefinition p) => UnifiedPolicyStorageFactory.PropertiesMatch(p, CS$ < > 8__locals2.incrementalCollectionProp));
                    PropertyDefinition propertyDefinition = propertyDefinitions.FirstOrDefault((PropertyDefinition p) => p.Name == UnifiedPolicyStorageFactory.GetRemovedCollectionPropertyName(addedProperty));
                    if (addedProperty != null && propertyDefinition != null)
                    {
                        UnifiedPolicyStorageFactory.CopyIncrementalCollection(CS$ < > 8__locals2.incrementalCollectionProp, addedProperty, propertyDefinition, storage, baseConfiguration);
                    }
                }
            }
        }
Ejemplo n.º 25
0
        public ManageAdminsViewModel(ISubject subject, FacadeBase <AdminDisplayModel> facade)
        {
            this.subject = subject;
            this.facade  = facade;

            this.Admins = new ObservableCollection <AdminDisplayModel>(facade.GetAll());

            this.EditSelectedAdminCommand = new DelegateCommand(
                () => RaiseAdminEditEvent(SelectedAdmin),
                obj => SelectedAdmin != null);
            this.DeleteSelectedAdminCommand = new DelegateCommand(
                () => RaiseAdminDeletedEvent(SelectedAdmin),
                obj => SelectedAdmin != null);

            subject.Subscribe(this);

            RaisePropertyChangedEvent("Admins");
            RaisePropertyChangedEvent("SelectedAdmin");
        }
Ejemplo n.º 26
0
        /// <summary>
        ///     匹配带引号的字符串
        /// </summary>
        /// <param name="facade">占位符</param>
        /// <param name="expr">表达式</param>
        /// <param name="c">引号(若为空表示任意)</param>
        // ReSharper disable once UnusedParameter.Global
        public static string Quoted(this FacadeBase facade, ref string expr, char?c = null)
        {
            expr = expr.TrimStart();
            if (expr.Length < 1)
            {
                return(null);
            }

            var ch = expr[0];

            if (c != null &&
                ch != c)
            {
                return(null);
            }

            var id = -1;

            while (true)
            {
                id = expr.IndexOf(ch, id + 2);
                if (id < 0)
                {
                    throw new ArgumentException("语法错误", nameof(expr));
                }

                if (id == expr.Length - 1)
                {
                    break;
                }
                if (expr[id + 1] != ch)
                {
                    break;
                }
            }

            var s = expr.Substring(0, id + 1);

            expr = expr.Substring(id + 1);
            return(s.Dequotation());
        }
Ejemplo n.º 27
0
        public void GetFacadeTestCase()
        {
            Facade facade1 = null;
            Facade facade2 = null;

            GivenCreateFactory()
            .And("create facade", _ =>
            {
                facade1 = FacadeBase.Create <Facade>(Factory);
            })
            .When("get facade", _ =>
            {
                facade2 = facade1.GetFacade <Facade>();
            })
            .Then("Check result", facade =>
            {
                Assert.IsNotNull(facade2, "facade2 cannot be null");
                Assert.AreNotEqual(facade1, facade2, "facades match");
                Assert.AreEqual(1, facade1.CountCallGetFacade, "there should have been 1 call GetFacade");
                Assert.AreEqual(0, facade2.CountCallGetFacade, "there should have been 0 call GetFacade");
            })
            .Run();
        }
        private static void CopyPropertiesToStorage <T>(FacadeBase storage, T baseConfiguration) where T : PolicyConfigurationBase
        {
            PropertyBag propertyBag = (storage.InnerPropertyBag as UnifiedPolicyStorageBase).propertyBag;

            propertyBag.SetField(UnifiedPolicyStorageBaseSchema.WorkloadProp, baseConfiguration.Workload);
            propertyBag.SetField(ADObjectSchema.WhenCreatedRaw, (baseConfiguration.WhenCreatedUTC != null) ? baseConfiguration.WhenCreatedUTC.Value.ToString("yyyyMMddHHmmss'.0Z'") : null);
            propertyBag.SetField(ADObjectSchema.WhenChangedRaw, (baseConfiguration.WhenChangedUTC != null) ? baseConfiguration.WhenChangedUTC.Value.ToString("yyyyMMddHHmmss'.0Z'") : null);
            propertyBag.SetField(UnifiedPolicyStorageBaseSchema.PolicyVersion, baseConfiguration.Version.InternalStorage);
            IEnumerable <PropertyDefinition> propertyDefinitions = DalHelper.GetPropertyDefinitions(storage, false);

            using (IEnumerator <PropertyInfo> enumerator = UnifiedPolicyStorageFactory.GetReflectedProperties <T>().GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    PropertyInfo       prop = enumerator.Current;
                    PropertyDefinition propertyDefinition = propertyDefinitions.FirstOrDefault((PropertyDefinition p) => UnifiedPolicyStorageFactory.PropertiesMatch(p, prop));
                    if (propertyDefinition != null)
                    {
                        UnifiedPolicyStorageFactory.CopyPropertyToStorage(propertyDefinition, prop, storage.InnerPropertyBag, baseConfiguration);
                    }
                }
            }
        }
Ejemplo n.º 29
0
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (actionContext.Request.Headers.Authorization == null)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "need to send username and password in basic authentication, bruh");
                return;
            }

            //getting username and password:
            string undecodedParameters = actionContext.Request.Headers.Authorization.Parameter;
            string decodedParameters   = Encoding.UTF8.GetString(Convert.FromBase64String(undecodedParameters));

            string[] usernamePasswordArray = decodedParameters.Split(':');
            string   username = usernamePasswordArray[0];
            string   password = usernamePasswordArray[1];

            FacadeBase facade = fcs.Login(username, password, out ILoginToken token);

            if (facade != null)
            {
                if (facade is ILoggedInAirlineFacade)
                {
                    ILoggedInAirlineFacade      airlineFacade = (ILoggedInAirlineFacade)facade;
                    LoginToken <AirlineCompany> airlineToken  = (LoginToken <AirlineCompany>)token;
                    actionContext.Request.Properties["facade"] = airlineFacade;
                    actionContext.Request.Properties["token"]  = airlineToken;
                }
                else
                {
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "you are not allowed to do this, you are not an airline company user!");
                }

                return;
            }

            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "wrong credentials");
        }
Ejemplo n.º 30
0
        public bool TryLogin(string userName, string password, out LoginToken <IUser> token, out FacadeBase facadeBase)
        {
            Users user = new Users();

            token      = null;
            facadeBase = null;

            if (userName is null)
            {
                throw new ArgumentNullException($"username cannot be: {userName}");
            }
            if (password is null)
            {
                throw new ArgumentNullException($"password cannot be: {password}");
            }

            //in case it's admin "level 4"
            if (userName == "admin" && password == "9999")
            {
                if (_adminDAO.GetUserByUsername(userName).Equals(_userDAO.GetUserByUsername(userName)))
                {
                    if (user.Password == password)
                    {
                        token      = new LoginToken <Administrators>();
                        facadeBase = new LoggedInAdministratorFacade();
                        return(true);
                    }
                }
            }
            else
            {
                if (UserAuthentication.IsUserAuthorized(userName, password))
                {
                    if (user.UserRole == 1)
                    {
                        Administrators admin = _adminDAO.Get(user.ID);
                        token = new LoginToken <Administrators>()
                        {
                            User = admin
                        };
                        facadeBase = new LoggedInAdministratorFacade();
                        return(true);
                    }
                    else if (user.UserRole == 2)
                    {
                        Administrators admin = _adminDAO.Get(user.ID);
                        token = new LoginToken <Administrators>()
                        {
                            User = admin
                        };
                        facadeBase = new LoggedInAdministratorFacade();
                        return(true);
                    }
                    else if (user.UserRole == 3)
                    {
                        Administrators admin = _adminDAO.Get(user.ID);
                        token = new LoginToken <Administrators>()
                        {
                            User = admin
                        };
                        facadeBase = new LoggedInAdministratorFacade();
                        return(true);
                    }
                    else if (user.ID.Equals(_customerDAO.Get(user.ID)))
                    {
                        Customer customer = _customerDAO.Get(user.ID);
                        token = new LoginToken <Customer>()
                        {
                            User = customer
                        };
                        facadeBase = new LoggedInCustomerFacade();
                        return(true);
                    }
                    else
                    {
                        AirlineCompany airline = _airlineDAO.Get(user.ID);
                        token = new LoginToken <AirlineCompany>()
                        {
                            User = airline
                        };
                        facadeBase = new LoggedInAirlineFacade();
                        return(true);
                    }
                }
            }
            my_logger.Info($"Login Faild\n: username: {userName} password: {password},  Not excited!");
            return(false);
        }