public async Task <IActionResult> Index(IFormCollection request)
        {
            // Parse inputs as ints
            int.TryParse(request._str("account_id"), out int accountId);
            int.TryParse(request._str("role_id"), out int roleId);
            string accountName = request._str("account_name");

            // Validate to ensure the required fields were returned.
            if (accountId == 0 && String.IsNullOrEmpty(accountName) || roleId == 0)
            {
                return(BadRequest("Invalid role or account ID/Name provided"));
            }

            var account = await _Db.Accounts.Where(a => a.Name == accountName || a.Id == accountId).Include(i => i.AccountRoles).SingleOrDefaultAsync();

            var role = await _Db.Roles.FindAsync(roleId);

            // User account does not exist
            if (account == null)
            {
                return(NotFound("Account not found."));
            }

            // Stops a user from changing their own role
            if (account.Id == User.AccountId())
            {
                return(Unauthorized("You are not allowed to add your own groups"));
            }

            // Stop the target account from being added to the same role twice (Would cause a fatal crash)
            if (account.AccountRoles.Where(c => c.Role == role).FirstOrDefault() != null)
            {
                return(Conflict($"{account.Name} has already been assigned to {role.Name}"));
            }

            // Role doesn't exist
            if (role == null)
            {
                return(NotFound("Role not found."));
            }

            try
            {
                await _Db.AccountRoles.AddAsync(new Models.AccountRole
                {
                    AccountId = account.Id,
                    RoleId    = role.Id,
                });

                await _Db.SaveChangesAsync();

                _Logger.LogInformation("{0} has added the {1} role to {2}", User.AccountName(), role.Name, account.Name);
                return(Ok());
            }
            catch (Exception ex)
            {
                _Logger.LogWarning("AddRole: Error granting role to {0} : {1}", account.Name, ex.Message);
                return(BadRequest(ex.Message));
            }
        }
예제 #2
0
        public async Task <IActionResult> Join(IFormCollection request)
        {
            int        pilotId = request._str("pilot_id") == "" ? Request.Cookies.PreferredPilotId() : request._int("pilot_id");
            List <int> roleIds = request._str("role_ids") != "" ? request._str("role_ids").Split(',').Select(item => int.Parse(item)).ToList() : new List <int>();
            List <int> fitIds  = request._str("fit_ids").Split(',').Select(item => int.Parse(item)).ToList();

            Pilot pilot = await _Db.Pilots.FindAsync(pilotId);

            if (pilot == null)
            {
                return(NotFound("Pilot not found"));
            }

            if (fitIds.Count == 0)
            {
                return(BadRequest("You must select a fit before you can join the waitlist"));
            }

            try
            {
                WaitingPilot waitlist = new WaitingPilot
                {
                    PilotId            = pilot.CharacterID,
                    SelectedFits       = null,
                    SelectedRoles      = null,
                    RemovedByAccountId = null,
                    NewPilot           = false,
                    CreatedAt          = DateTime.UtcNow,
                    UpdatedAt          = DateTime.UtcNow
                };
                await _Db.AddAsync(waitlist);

                foreach (int id in fitIds)
                {
                    await _Db.AddAsync(new SelectedFit
                    {
                        FitId          = id,
                        WaitingPilotId = waitlist.Id
                    });
                }

                // Add Roles
                foreach (int id in roleIds)
                {
                    await _Db.AddAsync(new SelectedRole
                    {
                        FleetRoleId    = id,
                        WaitingPilotId = waitlist.Id
                    });
                }
                await _Db.SaveChangesAsync();

                return(Ok());
            }
            catch (Exception ex)
            {
                _Logger.LogWarning("{0} could not be added to the waitlist: {1}", pilot.CharacterName, ex.Message);
                return(BadRequest($"Could not add {pilot.CharacterName} to the waitlist {ex.Message}"));
            }
        }
예제 #3
0
        public async Task <IActionResult> Invite(int fleetId, int pilotId, IFormCollection request)
        {
            Fleet fleet = await _Db.Fleets.Where(c => c.Id == fleetId).Include(c => c.BossPilot).FirstOrDefaultAsync();

            if (fleet == null)
            {
                return(BadRequest("The fleet was not found"));
            }

            Pilot boss = await _Db.Pilots.FindAsync(fleet.BossPilotId);

            if (boss == null)
            {
                return(BadRequest("The fleet boss was not found"));
            }

            if (!boss.ESIValid)
            {
                return(Unauthorized("Could not validate the FCs ESI Tokens"));
            }

            await boss.UpdateToken();

            await _Db.SaveChangesAsync();

            try
            {
                long.TryParse(request._str("squadId"), out long squad_id);
                long.TryParse(request._str("wingId"), out long wing_id);

                DefaultSquad squadPosition;
                if (squad_id == 0)
                {
                    squadPosition = fleet.DefaultSquad();
                }
                else
                {
                    squadPosition = new DefaultSquad
                    {
                        squad_id = squad_id,
                        wing_id  = wing_id
                    };
                }

                var x = EsiWrapper.FleetInvite((AuthorizedCharacterData)boss, fleet.EveFleetId, squadPosition.squad_id, squadPosition.wing_id, pilotId);
                return(Ok());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
        public async Task <IActionResult> Index(IFormCollection request)
        {
            if (request._str("banReason") == "" || request._str("accountName") == "")
            {
                return(BadRequest());
            }

            int AdminId       = User.AccountId();
            var BannedAccount = await _Db.Accounts.FirstOrDefaultAsync(c => c.Name == request._str("accountName"));

            if (BannedAccount == null)
            {
                return(NotFound(string.Format("The account {0} was not found", request._str("accountName"))));
            }

            if (AdminId == BannedAccount.Id)
            {
                return(Forbid("You cannot ban yourself"));
            }

            try
            {
                Ban ban = new Ban()
                {
                    AdminId         = AdminId,
                    BannedAccountId = BannedAccount.Id,
                    Reason          = request._str("banReason"),
                    //Expires at is disabled until I can spend enough time to use a proper Jquery date picker
                    ExpiresAt = null,//Ban.BanExpiryDate(request["expires_at"]),


                    CreatedAt = DateTime.UtcNow,
                    UpdatedAt = DateTime.UtcNow
                };

                _Logger.LogInformation("{0} is issuing a ban against {1}", User.AccountName(), request._str("accountName"));

                await _Db.Bans.AddAsync(ban);

                await _Db.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                _Logger.LogWarning("Error issuing a new ban: {1}", ex.Message);
                return(BadRequest("Failed to issue ban."));
            }


            return(Ok());
        }
        public async Task <IActionResult> NewShip(IFormCollection request)
        {
            string hullType = request._str("ship_name");
            int    queue_id = request._int("queue_id");

            ShipType ship = await _Db.ShipTypes.Where(c => c.Name.ToLower() == hullType.ToLower()).FirstOrDefaultAsync();

            if (ship != null)
            {
                ship.Queue = (Queue)queue_id;
                await _Db.SaveChangesAsync();

                return(Accepted());
            }

            SearchResults x = await EsiWrapper.Search(hullType, true, SearchCategory.InventoryType);

            if (x.InventoryTypes == null)
            {
                return(NotFound($"{hullType} could not be found. Is the name spelt correctly?"));
            }

            await _Db.AddAsync(new ShipType
            {
                Id    = (int)x.InventoryTypes[0],
                Name  = hullType,
                Queue = (Queue)queue_id
            });

            await _Db.SaveChangesAsync();

            return(Ok());
        }
        public async Task <IActionResult> Update(IFormCollection request, int id)
        {
            var currentBan = await _Db.Bans.Include(c => c.BannedAccount).FirstOrDefaultAsync(c => c.Id == id);

            // If no ban was found return 404
            if (currentBan == null)
            {
                return(NotFound());
            }

            try
            {
                currentBan.Reason = request._str("banReason");
                //Expires at is disabled until I can spend enough time to use a proper Jquery date picker
                currentBan.ExpiresAt        = null;//Ban.BanExpiryDate(request["expires_at"]),
                currentBan.UpdatedByAdminId = User.AccountId();
                currentBan.UpdatedAt        = DateTime.UtcNow;

                _Logger.LogInformation("{0} is updating the ban against {1}", User.AccountName(), currentBan.BannedAccount.Name);
                await _Db.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                _Logger.LogWarning("Error updating ban (Ban Id: {0}): {1}", currentBan.Id, ex.Message);
                return(BadRequest("Failed to update ban."));
            }

            return(Ok());
        }
        public async Task <IActionResult> JabberNotificationSetting(IFormCollection request)
        {
            Account account = await _Db.Accounts.FindAsync(User.AccountId());

            account.JabberNotifications = (request._str("notificationsEnabled").ToLower() == "true")? true : false;

            await _Db.SaveChangesAsync();

            return(Ok());
        }
        public async Task <IActionResult> Revoke(IFormCollection request)
        {
            // Parse inputs as ints
            int.TryParse(request._str("accountId"), out int accountId);
            int.TryParse(request._str("roleId"), out int roleId);
            // Validate to ensure the required fields were returned.
            if (accountId == 0 || roleId == 0)
            {
                return(BadRequest("Invalid role or account ID provided"));
            }

            if (accountId == User.AccountId())
            {
                return(Unauthorized("You are not allowed to remove your own groups"));
            }

            var accountRole = await _Db.AccountRoles
                              .Where(ar => ar.AccountId == accountId && ar.RoleId == roleId)
                              .Include(ar => ar.Account)
                              .Include(ar => ar.Role).SingleOrDefaultAsync();

            if (accountRole == null)
            {
                return(NotFound());
            }

            try
            {
                _Db.Remove(accountRole);
                await _Db.SaveChangesAsync();

                _Logger.LogInformation("{0} role revoked from {1}", accountRole.Role.Name, accountRole.Account.Name);
                return(Ok());
            }
            catch (Exception ex)
            {
                _Logger.LogWarning("RemoveRole: Error revoking role from {0}: {1}", accountRole.Account.Name, ex.Message);
                return(BadRequest(ex.Message));
            }
        }
예제 #9
0
        public async Task <IActionResult> SaveAnnouncment(IFormCollection request)
        {
            try
            {
                Announcement announcement = new Announcement
                {
                    CreatorAdminId = User.AccountId(),
                    Type           = request._str("type") != "" ? request._str("type") : "primary",
                    Message        = request._str("message"),
                    CreatedAt      = DateTime.UtcNow
                };

                await _Db.AddAsync(announcement);

                await _Db.SaveChangesAsync();

                return(Ok());
            }
            catch (Exception ex)
            {
                _Logger.LogError("Error creating an announcment. The admin was {0}: {1}", User.AccountName(), ex.Message);
                return(BadRequest(ex.Message));
            }
        }
        public async Task <IActionResult> Fit(IFormCollection request)
        {
            int currentFits = await _Db.Fits.Where(c => c.AccountId == User.AccountId() && !c.IsShipScan && c.DeletedAt == null).CountAsync();

            // Accounts are only allowed five fits at a time
            if (currentFits >= 5)// Does not take into account fits added by an FC through the fit scanner
            {
                return(BadRequest("You have reached your five ship limit. Please delete a ship before saving a new one"));
            }

            FitDna fitUrlObject;

            try
            {
                fitUrlObject = Util.ParseFitDna(request._str("fitUrl"));

                await ShipType.EnsureInDatabase(fitUrlObject.ship_typeId, _Db);

                Fit newFit = new Fit
                {
                    AccountId   = User.AccountId(),
                    ShipTypeId  = fitUrlObject.ship_typeId,
                    FittingDNA  = fitUrlObject.dna,
                    Description = fitUrlObject.description,
                    IsShipScan  = false,
                    CreatedAt   = DateTime.UtcNow
                };

                // Save new fit
                await _Db.AddAsync(newFit);

                await _Db.SaveChangesAsync();

                return(Ok());
            }
            catch (Exception ex)
            {
                _Logger.LogError("{0} submitted an invalid fit URL {1}: {2}", User.AccountName(), request._str("fitUrl"), ex.Message);
                return(BadRequest(ex.Message));
            }
        }
예제 #11
0
        public async Task <IActionResult> Leave(IFormCollection request)
        {
            List <WaitingPilot> waitingPilots;

            if (request._str("pilot_id") == "")
            {
                waitingPilots = await _Db.WaitingPilots.Include(c => c.Pilot).Where(c => c.Pilot.AccountId == User.AccountId() && c.RemovedByAccount == null).ToListAsync();
            }
            else
            {
                waitingPilots = await _Db.WaitingPilots.Where(c => c.PilotId == request._int("pilot_id") && c.RemovedByAccount == null).ToListAsync();
            }

            foreach (WaitingPilot pilot in waitingPilots)
            {
                pilot.RemovedByAccountId = User.AccountId();
            }

            await _Db.SaveChangesAsync();

            return(Ok());
        }
예제 #12
0
        public async Task <IActionResult> Type(IFormCollection request, int fleetId)
        {
            var fleet = await _Db.Fleets.Where(c => c.Id == fleetId && c.ClosedAt == null).FirstOrDefaultAsync();

            if (fleet == null)
            {
                // Fleet not found
                return(NotFound("Fleet not found."));
            }

            try
            {
                fleet.Type = request._str("type");
                await _Db.SaveChangesAsync();

                return(Ok());
            }
            catch (Exception ex)
            {
                _Logger.LogError("Cannot change the fleet type (Fleet ID: {0}) Type: {1} {2}.", fleet.Id, fleet.Type, ex.Message);
                return(BadRequest("Error setting fleet type."));
            }
        }
예제 #13
0
        public async Task <IActionResult> Index(IFormCollection request)
        {
            string EsiUrl = request._str("EsiFleetUrl");
            long   fleetId;

            try
            {
                fleetId = request._str("EsiFleetUrl").GetEsiId();
            }
            catch (Exception ex)
            {
                _Logger.LogError("Cannot parse the ESI Fleet ID from the URL provided. {0}", EsiUrl);
                return(BadRequest(string.Format("Cannot parse the ESI Fleet ID from the URL provided. {0}\n{1}", EsiUrl, ex.Message)));
            }

            int   bossId = request._int("fleetBoss");
            Pilot pilot  = await _Db.Pilots.Where(c => c.CharacterID == bossId && c.AccountId == User.AccountId()).FirstOrDefaultAsync();

            if (pilot == null)
            {
                return(NotFound("Pilot not found, or you do not have access to it."));
            }

            string fleetType = request._str("FleetType");

            //Is there an active fleet with this ID? IF yes redirect to that fleet else continue
            var fleet = await _Db.Fleets.Where(c => c.EveFleetId == fleetId && c.ClosedAt == null).FirstOrDefaultAsync();

            if (fleet != null)
            {
                // Fleet already registered let's redirect the user to that page.
                return(Ok(fleet.Id));
            }

            CommChannel comms = await _Db.CommChannels.FindAsync(request._int("FleetComms"));

            if (comms == null)
            {
                // Fleet comms not found
                _Logger.LogError("Invalid Comms channel provided.");
            }


            // TODO: Can we actually ESI into this fleet?
            if (false)
            {
                _Logger.LogWarning("(ID: {0}) does not have access to fleet {1}.", bossId, fleetId);
                return(Forbid("Pilot selected does not have access to that fleet. Check you selected the correct fleet boss!"));
            }

            Fleet newFleet = new Fleet
            {
                EveFleetId    = fleetId,
                BossPilot     = pilot,
                CommChannelId = comms.Id,
                IsPublic      = false,
                Type          = fleetType,
                CreatedAt     = DateTime.UtcNow,
                UpdatedAt     = DateTime.UtcNow
            };

            await _Db.AddAsync(newFleet);

            await _Db.SaveChangesAsync();

            // Redirect to page!
            return(Ok(newFleet.Id));
        }