public string[] GetAllRoles()
 {
     using (var database = new BonoboGitServerContext())
     {
         return database.Roles.Select(i => i.Name).ToArray();
     }
 }
        public IList<RepositoryModel> GetAllRepositories()
        {
            using (var db = new BonoboGitServerContext())
            {
                var dbrepos = db.Repositories.Select(repo => new
                {
                    Name = repo.Name,
                    Group = repo.Group,
                    Description = repo.Description,
                    AnonymousAccess = repo.Anonymous,
                    Users = repo.Users.Select(i => i.Username),
                    Teams = repo.Teams.Select(i => i.Name),
                    Administrators = repo.Administrators.Select(i => i.Username),
                    AuditPushUser = repo.AuditPushUser,
                    Logo = repo.Logo
                }).ToList();

                return dbrepos.Select(repo => new RepositoryModel
                {
                    Name = repo.Name,
                    Group = repo.Group,
                    Description = repo.Description,
                    AnonymousAccess = repo.AnonymousAccess,
                    Users = repo.Users.ToArray(),
                    Teams = repo.Teams.ToArray(),
                    Administrators = repo.Administrators.ToArray(),
                    AuditPushUser = repo.AuditPushUser,
                    Logo = repo.Logo
                }).ToList();
            }
        }
        public bool Create(TeamModel model)
        {
            if (model == null) throw new ArgumentException("team");
            if (model.Name == null) throw new ArgumentException("name");

            using (var database = new BonoboGitServerContext())
            {
                var team = new Team
                {
                    Name = model.Name,
                    Description = model.Description
                };
                database.Teams.Add(team);
                if (model.Members != null)
                {
                    AddMembers(model.Members, team, database);
                }
                try
                {
                    database.SaveChanges();
                }
                catch (UpdateException)
                {
                    return false;
                }
            }

            return true;
        }
 public bool AllowsAnonymous(string project)
 {
     using (var database = new BonoboGitServerContext())
     {
         var isAllowsAnonymous = database.Repositories.Any(repo => repo.Name == project && repo.Anonymous);
         return isAllowsAnonymous;
     }
 }
 public bool IsRepositorySenior(string username, string project)
 {
     using (var database = new BonoboGitServerContext())
     {
         username = username.ToLowerInvariant();
         var isRepoAdmin = database.Users.Where(us => us.Username == username).Any(us => (us.AdministratedRepositories.Any(ar => ar.Name == project)));
         return isRepoAdmin;
     }
 }
        public RepositoryModel GetRepository(string name)
        {
            if (name == null) throw new ArgumentException("name");

            using (var db = new BonoboGitServerContext())
            {
                return ConvertToModel(db.Repositories.FirstOrDefault(i => i.Name == name));
            }
        }
 public void CreateRole(string roleName)
 {
     using (var database = new BonoboGitServerContext())
     {
         database.Roles.Add(new Role
         {
             Name = roleName,
         });
     }
 }
 public string[] FindUsersInRole(string roleName, string usernameToMatch)
 {
     using (var database = new BonoboGitServerContext())
     {
         var users = database.Users
             .Where(us => us.Username.Contains(usernameToMatch) && us.Roles.Any(role => role.Name == roleName))
             .Select(us => us.Username)
             .ToArray();
         return users;
     }
 }
        public TeamModel GetTeam(string name)
        {
            if (name == null) throw new ArgumentException("name");

            using (var db = new BonoboGitServerContext())
            {
                var team = db.Teams.FirstOrDefault(i => i.Name == name);
                return team == null ? null : new TeamModel
                {
                    Name = team.Name,
                    Description = team.Description,
                    Members = team.Users.Select(m => m.Username).ToArray(),
                };
            }
        }
        public void Delete(string name)
        {
            if (name == null) throw new ArgumentException("name");

            using (var db = new BonoboGitServerContext())
            {
                var team = db.Teams.FirstOrDefault(i => i.Name == name);
                if (team != null)
                {
                    team.Repositories.Clear();
                    team.Users.Clear();
                    db.Teams.Remove(team);
                    db.SaveChanges();
                }
            }
        }
        public void Delete(string name)
        {
            if (name == null) throw new ArgumentException("name");

            using (var db = new BonoboGitServerContext())
            {
                var repo = db.Repositories.FirstOrDefault(i => i.Name == name);
                if (repo != null)
                {
                    repo.Administrators.Clear();
                    repo.Users.Clear();
                    repo.Teams.Clear();
                    db.Repositories.Remove(repo);
                    db.SaveChanges();
                }
            }
        }
        public IList<TeamModel> GetAllTeams()
        {
            using (var db = new BonoboGitServerContext())
            {
                var dbTeams = db.Teams.Select(team => new
                {
                    Name = team.Name,
                    Description = team.Description,
                    Members = team.Users.Select(i => i.Username),
                    Repositories = team.Repositories.Select(m => m.Name),
                }).ToList();

                return dbTeams.Select(item => new TeamModel
                {
                    Name = item.Name,
                    Description = item.Description,
                    Members = item.Members.ToArray(),
                }).ToList();
            }
        }
 public ActionResult ResetPassword(string digest)
 {
     string username;
     digest = HttpUtility.UrlDecode(digest, Encoding.UTF8);
     var cacheObj = MvcApplication.Cache[digest];
     if ( cacheObj != null )
     {
         using (var db = new BonoboGitServerContext())
         {
             username = cacheObj.ToString();
             var user = db.Users.FirstOrDefault(x => x.Username.Equals(username, StringComparison.OrdinalIgnoreCase));
             return View(new ResetPasswordModel { Username = username });
         }
     }
     else
     {
         ModelState.AddModelError("", "Password reset link was not valid");
         return RedirectToAction("Index", "Home");    
     }
 }
        public void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            using (var database = new BonoboGitServerContext())
            {
                usernames = usernames.Select(i => i.ToLowerInvariant()).ToArray();

                var roles = database.Roles.Where(i => roleNames.Contains(i.Name)).ToList();
                var users = database.Users.Where(i => usernames.Contains(i.Username)).ToList();

                foreach (var role in roles)
                {
                    foreach (var user in users)
                    {
                        role.Users.Add(user);
                    }
                }

                database.SaveChanges();
            }
        }
 public ActionResult ResetPassword(ResetPasswordModel model)
 {
     if (ModelState.IsValid)
     {
         using (var db = new BonoboGitServerContext())
         {
             var user = db.Users.FirstOrDefault(x => x.Username.Equals(model.Username, StringComparison.OrdinalIgnoreCase));
             if (user == null)
             {
                 TempData["ResetSuccess"] = false;
                 Response.AppendToLog("FAILURE");
             }
             else
             {
                 MembershipService.UpdateUser(model.Username, user.Name, user.Surname, user.Email, model.Password);
                 TempData["ResetSuccess"] = true;
             }
         }
     }
     return View(model);
 }
        public bool HasPermission(string username, string project)
        {
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(project))
                return false;

            using (var database = new BonoboGitServerContext())
            {
                username = username.ToLowerInvariant();
                var user = database.Users.FirstOrDefault(i => i.Username == username);
                var repository = database.Repositories.FirstOrDefault(i => i.Name == project);
                if (user != null && project != null)
                {
                    if (user.Roles.FirstOrDefault(i => i.Name == Definitions.Roles.Administrator) != null
                     || user.Repositories.FirstOrDefault(i => i.Name == project) != null
                     || user.AdministratedRepositories.FirstOrDefault(i => i.Name == project) != null
                     || user.Teams.Select(i => i.Name).FirstOrDefault(t => repository.Teams.Select(i => i.Name).Contains(t)) != null)
                    {
                        return true;
                    }
                }
            }
            return false;
        }
        public bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            using (var database = new BonoboGitServerContext())
            {
                var role = database.Roles.FirstOrDefault(i => i.Name == roleName);
                if (role != null)
                {
                    if (throwOnPopulatedRole)
                    {
                        if (role.Users.Count > 0)
                        {
                            throw new InvalidOperationException("Can't delete role with members.");
                        }
                    }

                    database.Roles.Remove(role);
                    database.SaveChanges();
                    return true;
                }

                return false;
            }
        }
 public string[] GetRolesForUser(string username)
 {
     using (var database = new BonoboGitServerContext())
     {
         username = username.ToLowerInvariant();
         var roles = database.Roles
             .Where(role => role.Users.Any(us => us.Username == username))
             .Select(role => role.Name)
             .ToArray();
         return roles;
     }
 }
        private void AddMembers(IEnumerable<string> users, IEnumerable<string> admins, IEnumerable<string> teams, Repository repo, BonoboGitServerContext database)
        {
            if (admins != null)
            {
                var administrators = database.Users.Where(i => admins.Contains(i.Username));
                foreach (var item in administrators)
                {
                    repo.Administrators.Add(item);
                }
            }

            if (users != null)
            {
                var permittedUsers = database.Users.Where(i => users.Contains(i.Username));
                foreach (var item in permittedUsers)
                {
                    repo.Users.Add(item);
                }
            }

            if (teams != null)
            {
                var permittedTeams = database.Teams.Where(i => teams.Contains(i.Name));
                foreach (var item in permittedTeams)
                {
                    repo.Teams.Add(item);
                }
            }
        }
        public void UpdateUserTeams(string userName, List<string> newTeams)
        {
            if (string.IsNullOrEmpty(userName)) throw new ArgumentException("userName");
            if (newTeams == null) throw new ArgumentException("newTeams");

            using (var db = new BonoboGitServerContext())
            {
                var user = db.Users.FirstOrDefault(u => u.Username == userName.ToLower());
                if (user != null)
                {
                    user.Teams.Clear();
                    var teams = db.Teams.Where(t => newTeams.Contains(t.Name));
                    foreach (var team in teams)
                    {
                        user.Teams.Add(team);
                    }
                    db.SaveChanges();
                }
            }
        }
 private void AddMembers(IEnumerable<string> members, Team team, BonoboGitServerContext database)
 {
     var users = database.Users.Where(i => members.Contains(i.Username));
     foreach (var item in users)
     {
         team.Users.Add(item);
     }
 }
        public void Update(RepositoryModel model)
        {
            if (model == null) throw new ArgumentException("model");
            if (model.Name == null) throw new ArgumentException("name");

            using (var db = new BonoboGitServerContext())
            {
                var repo = db.Repositories.FirstOrDefault(i => i.Name == model.Name);
                if (repo != null)
                {
                    repo.Group = model.Group;
                    repo.Description = model.Description;
                    repo.Anonymous = model.AnonymousAccess;
                    repo.AuditPushUser = model.AuditPushUser;

                    if (model.Logo != null)
                        repo.Logo = model.Logo;

                    if (model.RemoveLogo)
                        repo.Logo = null;

                    repo.Users.Clear();
                    repo.Teams.Clear();
                    repo.Administrators.Clear();

                    AddMembers(model.Users, model.Administrators, model.Teams, repo, db);

                    db.SaveChanges();
                }
            }
        }
 public bool RoleExists(string roleName)
 {
     using (var database = new BonoboGitServerContext())
     {
         return database.Roles.Any(i => i.Name == roleName);
     }
 }
 public bool IsUserInRole(string username, string roleName)
 {
     using (var database = new BonoboGitServerContext())
     {
         username = username.ToLowerInvariant();
         bool isInRole = database.Roles.Any(role => role.Name == roleName && role.Users.Any(us => us.Username == username));
         return isInRole;
     }
 }
        public void Update(TeamModel model)
        {
            if (model == null) throw new ArgumentException("team");
            if (model.Name == null) throw new ArgumentException("name");

            using (var db = new BonoboGitServerContext())
            {
                var team = db.Teams.FirstOrDefault(i => i.Name == model.Name);
                if (team != null)
                {
                    team.Description = model.Description;
                    team.Users.Clear();
                    if (model.Members != null)
                    {
                        AddMembers(model.Members, team, db);
                    }
                    db.SaveChanges();
                }
            }
        }
        public bool Create(RepositoryModel model)
        {
            if (model == null) throw new ArgumentException("model");
            if (model.Name == null) throw new ArgumentException("name");

            using (var database = new BonoboGitServerContext())
            {
                var repository = new Repository
                {
                    Name = model.Name,
                    Logo = model.Logo,
                    Group = model.Group,
                    Description = model.Description,
                    Anonymous = model.AnonymousAccess,
                    AuditPushUser = model.AuditPushUser,
                };
                database.Repositories.Add(repository);
                AddMembers(model.Users, model.Administrators, model.Teams, repository, database);
                try
                {
                    database.SaveChanges();
                }
                catch (UpdateException)
                {
                    return false;
                }
            }

            return true;
        }
 public ActionResult ForgotPassword(ForgotPasswordModel model)
 {
     if (ModelState.IsValid)
     {
         using (var db = new BonoboGitServerContext())
         {
             var user = db.Users.FirstOrDefault(x => x.Username.Equals(model.Username, StringComparison.OrdinalIgnoreCase));
             if (user == null)
             {
                 ModelState.AddModelError("", Resources.Home_ForgotPassword_UserNameFailure);
                 Response.AppendToLog("FAILURE");
             }
             else
             {
                 string token = MembershipService.GenerateResetToken(model.Username);
                 MvcApplication.Cache.Add(token, model.Username, DateTimeOffset.Now.AddHours(1));
                 TempData["SendSuccess"] = MembershipHelper.SendForgotPasswordEmail(user, token);
             }
         }
     }
     return View(model);
 }