private async Task<LoginTokenResponse> TryLogin(LoginToken loginToken) { var response = await _baseStreamsService.Login(loginToken.Username, loginToken.Password, CancellationToken.None); return new LoginTokenResponse { FavoriteTeam = response.FavTeam, Token = response.Token }; }
public async Task<LoginTokenResponse> Get(LoginToken loginToken) { try { return await TryLogin(loginToken); } catch (ApiException ex) { return new LoginTokenResponse { Message = ex.Message }; } }
// 6. Create Random Ticket From API Web. public void ReadTicketsFromAPI(int times) { int success = 0; IList <Customer> customers = adminFacade.GetAllCustomers(adminToken); IList <Flight> flights = new AnonymousUserFacade().GetAllFlights(); MainWindow.m_Dispatcher.Invoke(DispatcherPriority.ApplicationIdle, new ThreadStart(new Action(() => ViewModel.Logger.Add("Start Create Tickets...")))); User user; for (int i = 0; i < userNamesOfCustomers.Count; i++) { user = new User(adminFacade.GetCustomerByUserName(adminToken, userNamesOfCustomers[i]).User_Name, adminFacade.GetCustomerByUserName(adminToken, userNamesOfCustomers[i]).Password, UserType.Customer, true); FlyingCenterSystem.GetUserAndFacade(user, out ILogin token, out FacadeBase facade); LoginToken <Customer> customerToken = token as LoginToken <Customer>; LoggedInCustomerFacade customerFacade = new LoggedInCustomerFacade(); for (int j = 0; j < times; j++) { HttpResponseMessage response = client.GetAsync("").Result; if (response.IsSuccessStatusCode) { APIUser ticketAPI = response.Content.ReadAsAsync <APIUser>().Result; customerFacade.PurchaseTicket(customerToken, flights[j]); MainWindow.m_Dispatcher.Invoke(DispatcherPriority.ApplicationIdle, new ThreadStart(new Action(() => ViewModel.Logger[ViewModel.Logger.Count - 1] = $"- {success+1}/{times * userNamesOfCustomers.Count} Tickets Was Generated."))); success++; } ViewModel.HowMuchCreated++; } } userNamesOfCustomers = new List <string>(); if (times > 0) { log.Info($"\n{success} Tickets Were Created And {times - success} Failed.\n"); MainWindow.m_Dispatcher.Invoke(DispatcherPriority.ApplicationIdle, new ThreadStart(new Action(() => ViewModel.Logger.Add($"- Tickets Generator Is Over. ({success} Were Created And {times - success} Failed).")))); } else { MainWindow.m_Dispatcher.Invoke(DispatcherPriority.ApplicationIdle, new ThreadStart(new Action(() => ViewModel.Logger[ViewModel.Logger.Count - 1] = $"- No Creation Request For Tickets."))); } }
// Change Details Of Current Airline (Without Password). public void MofidyAirlineDetails(LoginToken <AirlineCompany> token) { if (UserIsValid(token)) { User airlineUser = _userDAO.GetUserByUserName(token.User.User_Name); if (airlineUser != null) { _userDAO.UpdateUserName(airlineUser.UserName, token.User.User_Name); _airlineDAO.Update(token.User); _backgroundDAO.AddNewAction(Categories.AirlineCompanies | Categories.Updates, $"Company: {token.User.User_Name} Tried To Update Her Details.", true); } else { _backgroundDAO.AddNewAction(Categories.AirlineCompanies | Categories.Updates, $"Company: {token.User.User_Name} Tried To Update Her Details.", false); throw new UserNotExistException($"Sorry, But '{token.User.User_Name}' Does Not Exist."); } } else { _backgroundDAO.AddNewAction(Categories.AirlineCompanies | Categories.Updates, $"Anonymous User Tried To Update Some Airline Company.", false); } }
public static Guid GenerateToken(int LoginID, string ipaddress) { // use for localhost if (ipaddress == null) { ipaddress = "localhost"; } using (TimechasersEntities te = new TimechasersEntities()) { Guid guid = Guid.NewGuid(); LoginToken persoon = te.LoginToken.Add(new LoginToken() { Token = guid, Timestamp = DateTime.Now, LoginID = LoginID, IPAdress = ipaddress }); te.SaveChanges(); return(guid); } }
public static Login ValidateToken(Guid token, string ipaddress) { // use for localhost if (ipaddress == null || token == Guid.Parse("4004d869-f629-4acd-8360-2475d7270fce")) { ipaddress = "localhost"; } using (TimechasersEntities te = new TimechasersEntities()) { DateTime expiryDate = DateTime.Now.AddHours(-(24 * 300)); LoginToken loginToken = te.LoginToken.Where(c => c.Token == token && c.Timestamp > expiryDate && c.IPAdress == ipaddress).FirstOrDefault(); if (loginToken == null || !loginToken.LoginID.HasValue) { return(null); } else { return(GetLoginById(loginToken.LoginID.Value)); } } }
public bool TryGetConnector(out ILoggedInAirlineFacade airlineFacade, out LoginToken <AirlineCompany> token) { if (Request.Properties["facade"] != null && Request.Properties["token"] != null) { if (Request.Properties["facade"] is ILoggedInAirlineFacade && Request.Properties["token"] is LoginToken <AirlineCompany> ) { airlineFacade = (ILoggedInAirlineFacade)Request.Properties["facade"]; token = (LoginToken <AirlineCompany>)Request.Properties["token"]; return(true); } } airlineFacade = null; token = null; return(false); //ILoginToken token; //airlineFacade = (ILoggedInAirlineFacade)fcs.Login("DeltaRune", "UnderTale", out token); //return token; }
public IHttpActionResult PurchaseTicket([FromUri] int flightID) { if (flightID <= 0) { return(BadRequest()); } LoginToken <Customer> token = (LoginToken <Customer>)Request.Properties["User"]; LoggedInCustomerFacade facade = (LoggedInCustomerFacade)(FlyingCenterSystem.GetFlyingCenterSystem().GetFacade(token)); Flight flight = facade.GetFlightById(flightID); if (flight == null) { return(StatusCode(HttpStatusCode.NoContent)); } Ticket t = facade.PurchaseTicket(token, flight); if (t == null) { return(NotFound()); } return(Ok()); }
public void ADD_COUNTRY() { bool actual = false; LoginService ls = new LoginService(); LoginToken <Administrator> ltAdmin = null; bool res = ls.TryAdminLogin("9999", "admin", out ltAdmin); if (res == true) { FlyingCenterSystem fs = FlyingCenterSystem.Instance; //ILoggedInAirLineFacade iAirlineCompanyFS = fs.GetFacade<ILoggedInAirLineFacade>(); //iAirlineCompanyFS.GetAllFlights(); ILoggedInAdministratorFacade iAdminFS = fs.GetFacade <ILoggedInAdministratorFacade>(); Country country = new Country(1, "Israel"); iAdminFS.CreateCountry(ltAdmin, country); if (country == iAdminFS.GetCountryByName(ltAdmin, "Israel")) { actual = true; } Assert.IsTrue(actual); } }
public IActionResult CancelFlight(long id) { LoginToken <AirlineCompany> airline_token = DesirializeToken(); Flight flight = _loggedInAirlineFacade.GetFlightById(id); if (flight == null) { return(NotFound()); } try { _loggedInAirlineFacade.CancelFlight(airline_token, flight); } catch (NotAllowedAirlineActionException) { return(Forbid()); } return(NoContent()); }
public IHttpActionResult CancelTicket([FromUri] int ticketid) { LoginToken <Customer> customerToken = (LoginToken <Customer>)Request.Properties["customerToken"]; LoggedInCustomerFacade custFacade = (LoggedInCustomerFacade)Request.Properties["customerFacade"]; TicketDAOMSSQL ticketDAO = new TicketDAOMSSQL(); Ticket ticket = ticketDAO.Get(ticketid); if (ticket == null || ticket.ID <= 0) { return(NotFound()); } try { custFacade.CancelTicket(customerToken, ticket); return(Ok()); } catch (Exception e) { return(Content(HttpStatusCode.NotAcceptable, e.Message)); } }
public ActionResult Login() { string sUN = Request["username"].ToString().Trim(); string sPW = Request["password"].ToString().Trim(); // make sure username and password aren't blank if (sUN.Length == 0 || sPW.Length == 0) { return(View("~/Views/Home/Login.cshtml", null)); } // make sure username is numeric and store it in sid int sid; bool IDisNumeric = int.TryParse(sUN, out sid); if (!IDisNumeric) { return(View("~/Views/Home/Login.cshtml", null)); } LoginToken LT = new LoginToken(); LT.password = sPW; LT.sellerID = sid; var sellerList = from n in db.Sellers where n.SellerID == LT.sellerID where n.Password == LT.password select n; if (sellerList.ToList().Count == 0) { return(View("~/Views/Home/Login.cshtml", null)); } sellerID = LT.sellerID; return(View("~/Views/Home/Index.cshtml", null)); }
{ // // Summary: // Calls when a process requests authorization. // // Parameters: // actionContext: // The action context, which encapsulates information for using System.Web.Http.Filters.AuthorizationFilterAttribute. public override void OnAuthorization(HttpActionContext actionContext) { string x = actionContext.Request.RequestUri.Authority; #region Authentication string authenticationRequest = actionContext.Request.Headers.Authorization.Parameter; string deCodedAuthenticationRequest = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationRequest)); string[] encodedAuthenticationRequest = deCodedAuthenticationRequest.Split(':'); string userName = encodedAuthenticationRequest[0]; string userPass = encodedAuthenticationRequest[1]; #endregion FlyingCenterSystem fly = FlyingCenterSystem.GetInstance(); LoginToken <AirLineCompanyLogin> token = new LoginToken <AirLineCompanyLogin>(); CompanyHelperClass.userLocalHost = x; fly.GetAirlineFacade(userName, userPass, out token); if (token != null) { actionContext.Request.GetRequestContext().Principal = new GenericPrincipal(new GenericIdentity(userName), null); Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(userPass), null); return; } else if (CompanyHelperClass.userLocalHost == x) { CompanyHelperClass.countNumOfEntries++; if (CompanyHelperClass.countNumOfEntries == 3) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, $"Uesr {CompanyHelperClass.userLocalHost}is blocked"); return; } actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "Worng password or user name"); } }
public void CancelFlight(LoginToken <AirlineCompany> token, Flight flight) { Execute(() => { if (token.User != flight.AirlineCompany) { throw new NotAllowedAirlineActionException($"Airline company {token.User.Name} not allowed to cancel flight {flight.Id} that belongs to {flight.AirlineCompany.Name}"); } IList <Ticket> tickets = _ticketDAO.GetTicketsByFlight(flight); if (tickets.Count > 0) { foreach (var ticket in tickets) { _flightsTicketsHistoryDAO.Add(ticket, TicketStatus.Cancelled_By_Company); _ticketDAO.Remove(ticket); } } _flightsTicketsHistoryDAO.Add(flight, FlightStatus.Cancelled_By_Company); _flightDAO.Remove(flight); }, new { Token = token, Flight = flight }, _logger); }
public void CREATE_FLIGHT2() { bool actual = false; LoginService ls = new LoginService(); LoginToken <AirLineCompany> ltAirLine = null; bool res = ls.TryAirLineLogin("kramnik", "KramnikAdmin", out ltAirLine); if (res == true) { FlyingCenterSystem fs = FlyingCenterSystem.Instance; ILoggedInAirLineFacade iAirlineCompanyFS = fs.GetFacade <ILoggedInAirLineFacade>(); DateTime dt1 = new DateTime(2020, 2, 21, 16, 15, 00); DateTime dt2 = new DateTime(2020, 2, 21, 08, 05, 00); Flight flight = new Flight(2, 1, 2, 1, dt1, dt2, 120); iAirlineCompanyFS.CreateFlight(ltAirLine, flight); if (flight == iAirlineCompanyFS.GetFlightByID(ltAirLine, 2)) { actual = true; } Assert.IsTrue(actual); } }
public void CancelTicketWrongUserForTicketException() { countryDAO.Add(new Country("Israel")); airlineDAO.Add(new AirlineCompany("ELAL", "ELALUSERNAME", "ELALPASSEORD", countryDAO.GetCountryByName("Israel").ID)); flightDAO.Add(new Flight(airlineDAO.GetAirlineByName("ELAL").ID, countryDAO.GetCountryByName("Israel").ID, countryDAO.GetCountryByName("Israel").ID, new DateTime(DateTime.Now.Year + 1, 12, 2), new DateTime(DateTime.Now.Year + 1, 12, 3), 30, FlightStatus.NotDeparted)); Flight flightOne = flightDAO.GetAll()[0]; customerDAO.Add(new Customer("FIRSTNAME", "LASTNAME", "USERNAME", "PASSWORD", "ADDRESS", "PNUMBER", "CNUMBER")); customerDAO.Add(new Customer("FIRSTNAME2", "LASTNAME2", "USERNAME2", "PASSWORD2", "ADDRESS2", "PNUMBER2", "CNUMBER2")); Customer customerOne = customerDAO.GetAll()[0]; Customer customerTwo = customerDAO.GetAll()[1]; LoginToken <Customer> customerLoggedIn = new LoginToken <Customer>(); customerLoggedIn.user = customerOne; ticketDAO.Add(new Ticket(flightOne.ID, customerTwo.ID)); Ticket ticket = ticketDAO.GetAll()[0]; facade.CancelTicket(customerLoggedIn, ticket); }
public void PurchaseTicketCustomerIDZeroException() { Country israel = new Country("Israel"); countryDAO.Add(israel); israel = countryDAO.GetAll()[0]; AirlineCompany elal = new AirlineCompany("ELAL", "ELALUSERNAME", "ELALPASSWORD", israel.ID); airlineDAO.Add(elal); elal = airlineDAO.GetAll()[0]; Flight theFlight = new Flight(elal.ID, israel.ID, israel.ID, new DateTime((DateTime.Now.Year + 2), 12, 5, 14, 00, 00), new DateTime((DateTime.Now.Year + 2), 12, 7, 14, 00, 00), 50, FlightStatus.NotDeparted); flightDAO.Add(theFlight); theFlight = flightDAO.GetAll()[0]; LoginToken <Customer> loggedInCustomer = new LoginToken <Customer>(); loggedInCustomer.user = new Customer(); facade.PurchaseTicket(loggedInCustomer, theFlight); }
public void GetAllMyTickets() { countryDAO.Add(new Country("Israel")); airlineDAO.Add(new AirlineCompany("ELAL", "ELALUSERNAME", "ELALPASSEORD", countryDAO.GetCountryByName("Israel").ID)); airlineDAO.Add(new AirlineCompany("ARKIA", "ARKIAUSERNAME", "ARKIAPASSWORD", countryDAO.GetCountryByName("Israel").ID)); flightDAO.Add(new Flight(airlineDAO.GetAirlineByName("ELAL").ID, countryDAO.GetCountryByName("Israel").ID, countryDAO.GetCountryByName("Israel").ID, new DateTime(DateTime.Now.Year + 1, 12, 2), new DateTime(DateTime.Now.Year + 1, 12, 3), 30, FlightStatus.NotDeparted)); flightDAO.Add(new Flight(airlineDAO.GetAirlineByName("ARKIA").ID, countryDAO.GetCountryByName("Israel").ID, countryDAO.GetCountryByName("Israel").ID, new DateTime(DateTime.Now.Year + 1, 12, 2), new DateTime(DateTime.Now.Year + 1, 12, 3), 30, FlightStatus.NotDeparted)); flightDAO.Add(new Flight(airlineDAO.GetAirlineByName("ARKIA").ID, countryDAO.GetCountryByName("Israel").ID, countryDAO.GetCountryByName("Israel").ID, new DateTime(DateTime.Now.Year + 1, 12, 2), new DateTime(DateTime.Now.Year + 1, 12, 3), 30, FlightStatus.NotDeparted)); customerDAO.Add(new Customer("FIRSTNAME", "LASTNAME", "USERNAME", "PASSWORD", "ADDRESS", "PNUMBER", "CNUMBER")); ticketDAO.Add(new Ticket(flightDAO.GetAll()[0].ID, customerDAO.GetAll()[0].ID)); ticketDAO.Add(new Ticket(flightDAO.GetAll()[1].ID, customerDAO.GetAll()[0].ID)); ticketDAO.Add(new Ticket(flightDAO.GetAll()[2].ID, customerDAO.GetAll()[0].ID)); LoginToken <AirlineCompany> airlineLoggenIn = new LoginToken <AirlineCompany>(); airlineLoggenIn.user = airlineDAO.GetAirlineByName("ARKIA"); Assert.AreEqual(2, facade.GetAllMyTickets(airlineLoggenIn).Count); }
public void ModifyCustomerDetails(LoginToken <Customer> token, Customer customer) { if (token.CheckToken()) { if (token.User.Password == customer.Password) { if (token.User.Username == customer.Username) { customer = new Customer(token.User.Id, customer.FirstName, customer.LastName, token.User.Username, token.User.Password, customer.Address, customer.PhoneNo, customer.CreditCardNumber); _customerDAO.Update(customer); LoginToken.User = customer; } else { throw new UnauthorizedActionException("Usernames cannot be changed."); } } else { throw new WrongPasswordException("Incorrect Password."); } } }
public IHttpActionResult CreateNewCustomer([FromBody] HTTPCustomer customer) { if (customer.FirstName == null | customer.LastName == null | customer.Username == null | customer.Password == null | customer.Address == null | customer.PhoneNo == null | customer.CreditCardNumber == null) { return(BadRequest()); } LoginToken <Administrator> token = (LoginToken <Administrator>)Request.Properties["User"]; LoggedInAdministratorFacade facade = (LoggedInAdministratorFacade)(FlyingCenterSystem.GetFlyingCenterSystem().GetFacade(token)); try { facade.CreateNewCustomer(token, new Customer( -1, customer.FirstName, customer.LastName, customer.Username, customer.Password, customer.Address, customer.PhoneNo, customer.CreditCardNumber)); } catch (UsernameAlreadyExistsException) { return(StatusCode(HttpStatusCode.Conflict)); } return(Ok()); }
//Remove Some Customer. public void RemoveCustomer(LoginToken <Administrator> token, Customer customer) { if (UserIsValid(token) && customer != null) { User customerUser = _userDAO.GetUserByUserName(customer.User_Name); if (customerUser != null) { _customerDAO.Remove(customer); _userDAO.RemoveUserName(customerUser); _backgroundDAO.AddNewAction(Categories.Customers | Categories.Deletions, $"Admin {token.User.User_Name} Tried Delete Some Admin. Id: {customer.Id} ({customer.User_Name}).", true); } else { _backgroundDAO.AddNewAction(Categories.Customers | Categories.Deletions, $"Admin {token.User.User_Name} Tried Delete Some Admin. Id: {customer.Id} ({customer.User_Name}).", false); throw new UserNotExistException($"Sorry, But '{customer.User_Name}' Does Not Exist."); } _backgroundDAO.AddNewAction(Categories.Customers | Categories.Deletions, $"Admin {token.User.User_Name} Tried Delete Some Admin. Id: {customer.Id} ({customer.User_Name}).", customerUser != null); } else { _backgroundDAO.AddNewAction(Categories.Customers | Categories.Deletions, $"Anonymous User Tried Delete Some Airline Comapny. Id: {customer.Id} ({customer.User_Name}).", false); } }
public int SaveLoginToken(LoginToken loginToken) { using IDbConnection db = _connectionFactory.GetConnection; int userId = db.Query <int>(@"Select u.Id From [User] u Where u.UserName = @UserName", new { loginToken.UserName }).FirstOrDefault(); loginToken.UserId = userId; int loginTokenUserId = db.Query <int>(@"Select userId From [LoginToken] Where UserId = @userId", new { userId }).FirstOrDefault(); string query = loginTokenUserId > 0 ? @"update [LoginToken] Set AccessToken = @AccessToken, RefreshToken = @RefreshToken, AccessTokenExpiry = @AccessTokenExpiry, DeviceCode = @DeviceCode, DeviceName = @DeviceName, RefreshTokenExpiry = @RefreshTokenExpiry Where UserId = @UserId" : @"Insert into [LoginToken](UserId, AccessToken, RefreshToken, AccessTokenExpiry, DeviceCode, DeviceName, RefreshTokenExpiry) values (@UserId, @AccessToken, @RefreshToken, @AccessTokenExpiry, @DeviceCode, @DeviceName, @RefreshTokenExpiry)"; return(db.Execute(query, loginToken)); }
public bool TryCustomerLogin(string password, string userName, out LoginToken <Customer> loginToken) { bool res = false; loginToken = null; _customerDAO = new CustomerDAOMSSQL(); Customer cust = _customerDAO.GetCustomerByUserName(userName); if (!(cust is null)) { if (cust.password != password) { throw new WrongPasswordException("entered password is not correct"); } else { res = true; loginToken = new LoginToken <Customer>(); loginToken.User = cust; } } return(res); }
public void GetAllAirlineCompanies() { UserRepository testUr = new UserRepository("dad", "aes", RolesEnum.admin); Admin testAdmin = new Admin("dav,", "id", 3); FlyingCenterSystem.GetInstance().TryLogin(ur.UserName, ur.Password, out ILogin token, out FacadeBase facade); LoginToken <Admin> myToken = token as LoginToken <Admin>; LoggedInAdministratorFacade myFacade = facade as LoggedInAdministratorFacade; myFacade.CreateNewAdmin(myToken, testUr, testAdmin); Country country = new Country("Israel"); myFacade.CreateNewCountry(myToken, country); AirlineCompany airlineCompany = new AirlineCompany("ElALL", 1, country.ID); UserRepository airlineTestUr = new UserRepository("rad", "ass", RolesEnum.airline); myFacade.CreateNewAirline(myToken, airlineTestUr, airlineCompany, country); AnonymousUserFacade anonymousUserFacade = new AnonymousUserFacade(); List <AirlineCompany> airlineCompanies = (List <AirlineCompany>)anonymousUserFacade.GetAllAirlineCompanies(); Assert.IsNotNull(airlineCompanies); }
public void CreateACustomerAndAUserRepositoryForThatCustomer() { UserRepository testUr = new UserRepository("dad", "aes", RolesEnum.admin); Admin testAdmin = new Admin("dav,", "id", 3); FlyingCenterSystem.GetInstance().TryLogin(ur.UserName, ur.Password, out ILogin token, out FacadeBase facade); LoginToken <Admin> myToken = token as LoginToken <Admin>; LoggedInAdministratorFacade myFacade = facade as LoggedInAdministratorFacade; myFacade.CreateNewAdmin(myToken, testUr, testAdmin); Country country = new Country("Israel"); myFacade.CreateNewCountry(myToken, country); AnonymousUserFacade anonymousUserFacade = new AnonymousUserFacade(); Customer customer = new Customer("asd", "fgh", "adthv", "0506794532", "123479520589243", 2); UserRepository customerUserRepository = new UserRepository("rad", "ass", RolesEnum.customer); anonymousUserFacade.CreateCustomerAndUserRepository(customerUserRepository, customer); Customer customer1 = myFacade.GetCustomerByid(myToken, customer.ID.ToString()); Assert.AreEqual(customer.ID, customer1.ID); }
public FacadeBase GetFacade <T>(LoginToken <T> token) where T : IUser { try { if (typeof(T) == typeof(Administrator)) { return(new LoggedInAdministratorFacade()); } else if (typeof(T) == typeof(Customers)) { return(new LoggedInCustomerFacade()); } else if (typeof(T) == typeof(AirlineCompanies)) { return(new LoggedInAirlineFacade()); } } catch (Exception ex) { log.Error($"There is a problem to get facade check {ex}"); } return(new AnonymousUserFacade()); }
/// <summary> /// Customer buy a ticket /// </summary> /// <param name="token"></param> /// <param name="flight"></param> /// <returns></returns> public void PurchaseTicket(LoginToken <Customer> token, Flight flight) { if (CheckIfTokenIsValid(token)) { Flight flight1 = _flightDAO.Get(flight.ID); if (flight1 != null) { if (flight1.DepartureTime <= DateTime.Now.AddMinutes(15)) { Ticket ticket = new Ticket(flight.ID, token.User.ID); _ticketDAO.Add(ticket); _flightDAO.ReductionFlightTicket(flight.ID); return; } throw new FlightAlreadyDeparturException($"this flight with this ID: {flight.ID} has already departed"); } throw new DataNotFoundException($"there isn't an existing flight with this ID: {flight.ID} in the data base"); } else { throw new TokenIsNullException($"Token ID: {token.User.User_Repository_ID}"); } }
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"); }
public IHttpActionResult UpdateAirlineCompany(int airlineCompanyID, [FromBody] HTTPAirlineCompany airlineCompany) { if (airlineCompany.AirlineName == null & airlineCompany.Username == null & airlineCompany.Password == null & airlineCompany.CountryID <= 0) { return(BadRequest()); } LoginToken <Administrator> token = (LoginToken <Administrator>)Request.Properties["User"]; LoggedInAdministratorFacade facade = (LoggedInAdministratorFacade)(FlyingCenterSystem.GetFlyingCenterSystem().GetFacade(token)); AirlineCompany original = facade._airlineDAO.Get(airlineCompanyID); HTTPAirlineCompany tempAirline = new HTTPAirlineCompany(original); if (airlineCompany.AirlineName != null) { tempAirline.AirlineName = airlineCompany.AirlineName; } if (airlineCompany.Username != null) { tempAirline.Username = airlineCompany.Username; } if (airlineCompany.Password != null) { tempAirline.Password = airlineCompany.Password; } if (airlineCompany.CountryID > 0) { tempAirline.CountryID = airlineCompany.CountryID; } try { facade.UpdateAirlineDetails(token, new AirlineCompany(airlineCompanyID, tempAirline.AirlineName, tempAirline.Username, tempAirline.Password, tempAirline.CountryID)); } catch (UsernameAlreadyExistsException) { return(StatusCode(HttpStatusCode.Conflict)); } return(Ok()); }
public bool TryLogin(string password, string userName, out ILoginToken token) { bool res = false; LoginToken <Administrator> ltAdmin = null; res = TryAdminLogin(password, userName, out ltAdmin); //throw new FunnyException("HA HA"); if (res == false) { LoginToken <AirLineCompany> ltAirLineCompany = null; res = TryAirLineLogin(password, userName, out ltAirLineCompany); if (res == false) { LoginToken <Customer> ltCustomer = null; res = TryCustomerLogin(password, userName, out ltCustomer); if (res == false) { throw new UserNotFoundException("Not Found"); } else { token = ltCustomer; } } else { token = ltAirLineCompany; } } else { token = ltAdmin; } return(res); }
private void Button_Click(object sender, RoutedEventArgs e) { loginToken = FCS.Login(useNameTxt.Text, passwordTxt.Text); if (loginToken == null) { Border.DataContext = myBorderBackGroundRed; } else { LoginToken <AirlineCompany> airlineCompanyToken = loginToken as LoginToken <AirlineCompany>; if (airlineCompanyToken != null) { Border.DataContext = myBorderBackGroundGreen; flightList = new FlightsList(loginToken); flightList.Show(); // Hide the MainWindow until later //this.Hide(); this.Close(); } LoginToken <Customer> customerToken = loginToken as LoginToken <Customer>; if (customerToken != null) { buyTicket = new BuyTicket(loginToken); buyTicket.Show(); } LoginToken <Administrator> adminToken = loginToken as LoginToken <Administrator>; if (adminToken != null) { dbUpdate = new DBUpdate(loginToken); dbUpdate.Show(); } } }
/// <summary> /// Remove a customer by his UserRepositoryID /// </summary> /// <param name="token"></param> /// <param name="UserRepositoryID"></param> public void RemoveCustomer(LoginToken <Admin> token, string UserRepositoryID) { if (CheckIfTokenIsValid(token)) { long tryUserRepositoryID; bool trynum = long.TryParse(UserRepositoryID, out tryUserRepositoryID); if (trynum) { UserRepository userRepository = _userRepositoryDAO.Get(tryUserRepositoryID); if (userRepository != null) { Customer customer = _customerDAO.GetCustomerByUserRepositoryID(tryUserRepositoryID); if (customer != null) { _customerDAO.Remove(customer); } else { throw new DataNotFoundException($"there isn't an existing customer with this UserRepositoryID: {tryUserRepositoryID} in the data base"); } _userRepositoryDAO.Remove(userRepository); } else { throw new DataNotFoundException($"there isn't an existing UserRepository with this ID: {tryUserRepositoryID} in the data base"); } } if (!trynum) { throw new FormatException($"cant convert {UserRepositoryID} to a number"); } } else { throw new TokenIsNullException($"Token ID: {token.User.ID} is null"); } }
public TokenExpiredException(LoginToken token) : base(string.Format("This token expired on '{0}'!", token.Expire)) { this.Token = token; }
public static void Logout(LoginToken lt) { UserManagementService.InvalidateLoginToken(lt); }
private int GetCustomerId(LoginToken lt) { var user = UserManagementService.FindUserWithLoginToken(lt); var customer = CustomerManagementService.FindCustomerWithUserId(user.Id); return customer.Id; }
internal static void SetCopyleaksClient(this HttpClient client, string contentType, LoginToken SecurityToken) { client.SetCopyleaksClient(contentType); client.DefaultRequestHeaders.Add("Authorization", string.Format("{0} {1}", "Bearer", SecurityToken.Token)); }
/// <summary> /// Login to Ge.tt Web Service. /// The first method to call before any other service. /// </summary> /// <param name="apiKey">API Key</param> /// <param name="email">Email</param> /// <param name="password">Password</param> public bool Login(string apiKey, string email, string password) { // Argument var loginToken = new LoginToken { ApiKey = apiKey, Email = email, Password = password }; string jsonArgument = JsonConvert.SerializeObject(loginToken); // POST request var gett = new WebClient { Encoding = Encoding.UTF8 }; gett.Headers.Add("Content-Type", "application/json"); byte[] request = Encoding.UTF8.GetBytes(jsonArgument); byte[] response = gett.UploadData(UsersLogin, request); // Response Token = JsonConvert.DeserializeObject<UserToken>(Encoding.UTF8.GetString(response)); return Token.Expires.HasValue && Token.Expires > 0; }
public void Login(string username, string password, List<string> tokens) { Account account = null; string message; do { if (Session != null) { message = "You are already logged in."; break; } if (!Util.IsValidUsername(username)) { message = Util.InvalidUsernameMessage; break; } var existingTokens = LoginToken.FindAll(username).ToList(); if (String.IsNullOrEmpty(password)) { if (tokens.Count == 0) { message = "Missing password."; break; } if (!existingTokens.Any(t => t.Address == Address && tokens.Contains(t.Token))) { message = "Automatic login failed. Login with your username and password."; break; } account = Account.Get(username); tokens = existingTokens.Select(t => t.Token).ToList(); message = String.Format("Logged in as {0}.", account.Name); } else { if (!Util.IsValidPassword(password)) { message = Util.InvalidPasswordMessage; break; } account = Account.Get(username); if (account == null) { message = "Invalid username or password."; break; } var givenPassword = Convert.ToBase64String(Util.HashPassword(password, Convert.FromBase64String(account.Salt))); if (givenPassword != account.Password) { account = null; message = "Invalid username or password."; break; } LoginToken newToken = existingTokens.FirstOrDefault(t => t.Address == Address); if (newToken == null) { newToken = new LoginToken { Name = account.Name.ToLower(), Address = Address, Token = Util.GenerateLoginToken(), Created = Util.GetCurrentTimestamp() }; newToken.Insert(); existingTokens.Add(newToken); } tokens = existingTokens.Select(t => t.Token).ToList(); message = String.Format("Logged in as {0}.", account.Name); } } while (false); if (account != null) { Send(new AuthenticateResponse { Name = account.Name, Tokens = string.Join(",", tokens), Success = true }); var session = Program.SessionManager.GetOrCreate(account); session.Add(this); } SendSysMessage(message); }
private void VerifySession(LoginToken lt) { bool isValid = UserManagementService.ValidateLoginToken(lt); if (!isValid) throw new ApplicationException("Invalid session"); }