public IActionResult Delete([FromBody] User referee)
        {
            return(DbTransaction((c, t) => {
                if (referee == null)
                {
                    throw new NoDataException();
                }

                CheckAuthLevel(UserLevel.OrgAdmin);

                // TODO: Verify that no matches are assigned to this referee.

                // For now, assume it is a forced delete and remove referee from matches.
                var sql = @"
                    DELETE FROM matchreferees WHERE idUser = @idUser;
                    DELETE FROM users WHERE id = @idUser AND level = @level;
                ";

                var result = c.Execute(sql, new { idUser = referee.Id, level = (int)UserLevel.Referee }, t);

                PlayersController.DeleteUserInGlobalDirectory(Request, referee.Id);

                return result;
            }));
        }
예제 #2
0
        // __ Impl ____________________________________________________________


        private PlayerNotificationData GetPasswordResetNotifData(IDbConnection c, string email)
        {
            var user = GetUserForEmail(c, email);

            /*var mr = c.QueryMultiple(@"
             *      SELECT u.id, u.name, u.email, u.mobile, u.emailConfirmed FROM users u WHERE email ilike @email;
             *      SELECT id, name, logoImgUrl FROM organizations LIMIT 1;
             *  ", new { email = email });*/
            var mr = c.QueryFirst <PublicOrganization>(@"SELECT id, name, logoImgUrl FROM organizations LIMIT 1;");

            var toUser = user;
            //var toUser = mr.ReadFirst<User>();
            var fromUser = toUser;
            //var org = mr.ReadFirst<PublicOrganization>();
            var org = mr;

            var activationLink = PlayersController.GetActivationLink(Request, mTokenManager, toUser);

            var result = new PlayerNotificationData
            {
                From           = fromUser,
                To             = toUser,
                Org            = org,
                ActivationLink = activationLink,
                Images         = new PlayerInviteImages
                {
                    OrgLogo = Utils.GetUploadUrl(Request, org.LogoImgUrl, org.Id, "org"),
                }
            };

            return(result);
        }
        public IActionResult Create([FromBody] User referee)
        {
            return(DbTransaction((c, t) => {
                if (referee == null)
                {
                    throw new NoDataException();
                }
                if (!IsOrganizationAdmin())
                {
                    throw new UnauthorizedAccessException();
                }

                UsersController.CheckEmail(c, t, referee.Email);

                var dbUser = new User {
                    Name = referee.Name,
                    Email = referee.Email,
                    Mobile = referee.Mobile,
                    Lang = referee.Lang,
                    AvatarImgUrl = referee.AvatarImgUrl,
                    Level = (int)UserLevel.Referee,
                    Password = "",
                    Salt = "",
                    EmailConfirmed = false
                };

                var idUser = c.Insert(dbUser, t);

                SendInvitation(c, t, dbUser);

                PlayersController.AddUserToGlobalDirectory(Request, idUser, referee.Email);

                return idUser;
            }));
        }
        public IActionResult Edit([FromBody] User referee)
        {
            return(DbTransaction((c, t) => {
                if (referee == null)
                {
                    throw new NoDataException();
                }
                var isReferee = IsReferee();
                if (!IsOrganizationAdmin() && !isReferee)
                {
                    throw new UnauthorizedAccessException();
                }
                if (isReferee && (GetUserId() != referee.Id))
                {
                    throw new UnauthorizedAccessException();
                }

                var dbUser = c.Get <User>(referee.Id);
                if (dbUser == null)
                {
                    throw new Exception("Error.NotFound");
                }

                var isNewEmail = false;

                if (referee.Email != dbUser.Email)
                {
                    UsersController.CheckEmail(c, null, referee.Email);
                    isNewEmail = true;
                }

                Mapper.MapExplicit(referee, dbUser, new string[] {
                    "Name", "Email", "Mobile", "AvatarImgUrl"
                });

                if (!String.IsNullOrWhiteSpace(referee.Password))
                {
                    UsersController.UpdatePassword(dbUser, referee.Password);
                    dbUser.EmailConfirmed = true;
                }

                var result = c.Update(dbUser, t);

                if (isNewEmail)
                {
                    PlayersController.UpdateUserInGlobalDirectory(Request, dbUser.Id, referee.Email);
                }

                return result;
            }));
        }
        private PlayerNotificationData GetRefereeNotification(IDbConnection c, IDbTransaction t, long idUser, bool wantsPin)
        {
            var fromId = GetUserId();

            var mr = c.QueryMultiple(@"
                    SELECT u.id, u.name, u.email, u.mobile, u.emailConfirmed FROM users u WHERE id = @idUser;
                    SELECT id, name, logoImgUrl FROM organizations LIMIT 1;
                    SELECT u.id, u.name, u.email, u.mobile FROM users u WHERE id = @idFrom;
                ", new { idUser, idFrom = fromId });

            var toUser   = mr.ReadFirst <User>();
            var org      = mr.ReadFirst <PublicOrganization>();
            var fromUser = mr.ReadFirstOrDefault <User>();

            if (fromUser == null && fromId >= 10000000)
            {
                fromUser = UsersController.GetGlobalAdminForId(fromId);
            }

            if (toUser == null)
            {
                throw new Exception("Error.NotFound.ToUser");
            }
            if (fromUser == null)
            {
                throw new Exception("Error.NotFound.FromUser");
            }
            //if (fromUser == null) fromUser = new User { Id=1, Name=org.Name, Email="*****@*****.**" };

            var activationLink = toUser.EmailConfirmed && !wantsPin ? "" : PlayersController.GetActivationLink(Request, mAuthTokenManager, toUser);
            var activationPin  = toUser.EmailConfirmed && !wantsPin ? "" : UsersController.GetActivationPin(mAuthTokenManager, toUser);

            return(new PlayerNotificationData
            {
                From = fromUser,
                To = toUser,
                Org = org,
                ActivationLink = activationLink,
                ActivationPin = activationPin,
                Images = new PlayerInviteImages
                {
                    OrgLogo = Utils.GetUploadUrl(Request, org.LogoImgUrl, org.Id, "org"),
                }
            });
        }
예제 #6
0
        private PlayerNotificationData GetPlayerNotification(IDbConnection c, long idCreator, long idPlayer, long idTeam, bool wantsPin = false, long userId = -1)
        {
            var fromUser = UsersController.GetUserForId(c, idCreator);
            var toUser   = new User {
            };

            if (userId == -1) // User should exitst in current org
            {
                toUser = c.QueryFirst <User>($"SELECT u.id, u.name, u.mobile FROM users u JOIN players p ON p.idUser = u.id AND p.id = {idPlayer};");
                var userToGlobal = UsersController.GetUserForId(c, toUser.Id);
                toUser.Email          = userToGlobal.Email;
                toUser.EmailConfirmed = userToGlobal.EmailConfirmed;
            }
            else // Global User info
            {
                toUser = UsersController.GetUserForId(c, userId);
            }

            var mr = c.QueryMultiple(@"
                    SELECT id, name, logoImgUrl FROM organizations LIMIT 1;
                    SELECT id, name, logoImgUrl FROM teams WHERE id = @idTeam;
                ", new { idFrom = idCreator, idPlayer = idPlayer, idTeam = idTeam });

            // var fromUser = mr.ReadFirst<User>();
            // var toUser = mr.ReadFirst<User>();
            var org  = mr.ReadFirst <PublicOrganization>();
            var team = mr.ReadFirst <Team>();

            if (fromUser == null && idCreator >= 10000000)
            {
                fromUser = UsersController.GetGlobalAdminForId(idCreator);
            }

            if (team == null)
            {
                throw new Exception("Error.NotFound.Team");
            }
            if (toUser == null)
            {
                throw new Exception("Error.NotFound.ToUser");
            }
            if (fromUser == null)
            {
                throw new Exception("Error.NotFound.FromUser");
            }

            var activationLink = toUser.EmailConfirmed && !wantsPin ? "" : PlayersController.GetActivationLink(Request, mAuthTokenManager, toUser);
            var activationPin  = toUser.EmailConfirmed && !wantsPin ? "" : UsersController.GetActivationPin(mAuthTokenManager, toUser);

            return(new PlayerNotificationData
            {
                To = toUser,
                From = fromUser,
                Team = team,
                Org = org,
                ActivationLink = activationLink,
                ActivationPin = activationPin,
                Images = new PlayerInviteImages
                {
                    OrgLogo = Utils.GetUploadUrl(Request, org.LogoImgUrl, org.Id, "org"),
                    TeamLogo = Utils.GetUploadUrl(Request, team.LogoImgUrl, team.Id, "team")
                }
            });
        }
예제 #7
0
        public async Task <IActionResult> TeamUploadAsync([FromForm] TeamFile file)
        {
            // JSON file => string
            var stringBuilder = new StringBuilder();

            using (var reader = new StreamReader(file.File.OpenReadStream()))
            {
                while (reader.Peek() >= 0)
                {
                    stringBuilder.AppendLine(await reader.ReadLineAsync());
                }
            }
            string JSONString = stringBuilder.ToString();

            // Set file content to Team Object
            JObject jObjectTeam  = JObject.Parse(JSONString);
            Team    team         = jObjectTeam.ToObject <Team>();
            long    idTournamnet = file.IdTournament;

            return(DbOperation(conn =>
            {
                CheckAuthLevel(UserLevel.OrgAdmin);
                if (team == null)
                {
                    throw new NoDataException();
                }
                long idTeam = team.Id;

                // var existTeamQuery = conn.Query($"SELECT * FROM teams WHERE id = {team.Id} OR name = '{team.Name}' OR keyname = '{team.KeyName}';");

                // 🔎 External Org team can overrrite team.id values so will make query more restrictive
                var existTeamQuery = conn.Query($"SELECT * FROM teams WHERE id = {team.Id} AND name = '{team.Name}' AND keyname = '{team.KeyName}';");

                bool teamExitst = existTeamQuery.Count() > 0;

                if (!teamExitst)
                {
                    // Add team and add Team to Tournament
                    Audit.Information(this, "{0}: Teams.CreateInTournament {idTournament} -> {Name}", GetUserId(), team.Name, idTournamnet);
                    var teamId = conn.Insert(team);
                    idTeam = teamId;
                    conn.Insert(new TournamentTeam {
                        IdTournament = idTournamnet, IdTeam = teamId
                    });
                }
                else
                {
                    var existsTeamInTournamentQuery = conn.Query($"SELECT * FROM tournamentteams WHERE idtournament = {idTournamnet} AND idteam = '{idTeam}';");
                    bool existsTeamInTournament = existsTeamInTournamentQuery.Count() > 0;

                    if (!existsTeamInTournament)
                    {
                        // Add team just into tournamnet
                        Audit.Information(this, "{0}: Teams.AddToTournament {idTournament} -> {idTeam}", GetUserId(), idTournamnet, idTeam);

                        conn.Insert(new TournamentTeam {
                            IdTournament = idTournamnet, IdTeam = idTeam
                        });

                        // TODO: Notify team admin (if any) her team has been added to the competition.
                    }
                    if (existsTeamInTournament)
                    {
                        return new Exception("Error.Team_already_exitsts_in_tournament");
                    }
                }

                // 🚧🚧🚧 Add players to team
                foreach (var player in team.Players)
                {
                    if (player == null || player.UserData == null || player.TeamData == null)
                    {
                        throw new Exception("Malformed request");
                    }
                    Audit.Information(this, "{0}: Players.CreatePlayer {Name} {Surname}", GetUserId(), player.Name, player.Surname);

                    // User email should exists
                    bool userExists = PlayersController.CheckUserExistsInGlobalDirectory(Request, player.UserData.Id, player.UserData.Email);
                    if (!userExists)
                    {
                        throw new Exception($"{player.UserData.Email} does not exists in the global directory.");
                    }

                    var invite = new InviteInput {
                        IdPlayer = player.Id, IdTeam = idTeam, InviteText = "Hi, we want to invite you to join our team."
                    };                                                                                                                                  // 🚧 Lang

                    DbTransaction((c, t) =>
                    {
                        Audit.Information(this, "{0}: Players.Invite1: {IdTeam} {IdPlayer}", GetUserId(), invite.IdTeam, invite.IdPlayer);

                        if (!IsOrganizationAdmin() && !IsTeamAdmin(invite.IdTeam, c))
                        {
                            throw new UnauthorizedAccessException();
                        }

                        // Validate player is not already on the team.
                        var existingPlayer = c.ExecuteScalar <int>("SELECT COUNT(*) FROM teamplayers WHERE idteam = @idTeam AND idplayer = @idPlayer", invite, t);
                        if (existingPlayer > 0)
                        {
                            throw new Exception("Error.PlayerAlreadyInTeam");
                        }

                        invite.InviteText = mSanitizer.Sanitize(invite.InviteText);

                        var userOrg = c.QueryFirstOrDefault <User>($"SELECT * FROM users WHERE id = {player.IdUser}");
                        var notifData = new PlayerNotificationData {
                        };

                        if (userOrg == null)
                        {
                            // Insert player
                            var newPlayer = PlayersController.InsertPlayer(c, t, player, player.IdUser, GetUserId(), false, null, UserEventType.PlayerImported);
                            invite.IdPlayer = newPlayer.Id;

                            // Importing player that not exists in current org users
                            notifData = GetPlayerNotification(c, GetUserId(), invite.IdPlayer, invite.IdTeam, false, player.IdUser);
                        }
                        else
                        {
                            // Get current org player id becouse import Id can overlap
                            var playerOrg = c.QueryFirstOrDefault <Player>($"SELECT * FROM players WHERE iduser = {userOrg.Id}");
                            if (playerOrg == null)
                            {
                                throw new Exception("Error.PlayerNotFound");                   // Player should exist
                            }
                            invite.IdPlayer = playerOrg.Id;

                            notifData = GetPlayerNotification(c, GetUserId(), invite.IdPlayer, invite.IdTeam);
                        }

                        // Create the teamplayers record
                        var tp = new TeamPlayer
                        {
                            IdPlayer = invite.IdPlayer,
                            IdTeam = invite.IdTeam,
                            IsTeamAdmin = false,
                            Status = 1
                        };

                        c.Insert(tp, t);

                        // UserEvent

                        c.Insert(new UserEvent
                        {
                            IdCreator = GetUserId(),
                            IdUser = notifData.To.Id,
                            Type = (int)UserEventType.PlayerInvitedToTeam,
                            TimeStamp = DateTime.Now,
                            Description = notifData.Team.Name
                        }, t);

                        notifData.InviteMessage = invite.InviteText;

                        Audit.Information(this, "{0}: Players.Invite2: {1} {2}", GetUserId(), notifData.Team.Name, notifData.To.Name);

                        mNotifications.NotifyEmail(Request, c, t, TemplateKeys.EmailPlayerInviteHtml, notifData);

                        return true;
                    });
                }

                return true;
            }));
        }