public async Task <GroupDto> Handle(CreateGroupCommand request, CancellationToken cancellationToken)
        {
            var dto = request.Group;

            bool nameAlreadyUsed = await Database.Groups
                                   .AnyAsync(e => e.Name.Trim() == dto.Name.Trim());

            if (nameAlreadyUsed)
            {
                throw new BadRequestException($"{nameof(dto.Name)} '{dto.Name}' already used.");
            }

            var model = new Data.Models.Group()
            {
                Name     = dto.Name,
                IsActive = dto.IsActive
            };

            Database.Groups.Add(model);

            await Database.SaveChangesAsync();

            await Mediator.Publish(new GroupCreatedDomainEvent(model));

            return(Mapper.Map <GroupDto>(model));
        }
Beispiel #2
0
        public Group CreateGroup(Group group)
        {
            id += 1;
            string idGroup = "Group-";
            string idNum   = "";

            if (id < 10)
            {
                idNum = "00";
            }
            else if (id < 100)
            {
                idNum = "0";
            }
            else
            {
                idNum = "";
            }
            group.Id = idGroup + idNum + id;
            if (group.Name.Length <= 50 && group.Name != null)
            {
                Data.Models.Group groupToAdd = DTOMappers.MapGroup(group);
                _dbContext.AddGroup(groupToAdd);
            }
            return(group);
        }
Beispiel #3
0
 public AuthManager(IAdminManager admin, IUserManager umgr, ISmtpManager smgr, Config cfg)
 {
     Config                 = cfg;
     DefaultGroup           = admin.GroupManager.Get(cfg.DefaultGroupName);
     AdminGroup             = admin.GroupManager.Get(cfg.AdminGroupName);
     _providers["internal"] = new AuthProviderInternal(umgr, smgr, this);
 }
Beispiel #4
0
        public static void Initialize(AdminManager manager)
        {
#if DEBUG
            if (!manager._context.ApiKeys.Any(x => x.Description == "[WIKILIBS_SUPER_DEV_API_KEY]"))
            {
                manager.ApiKeyManager.PostAsync(new Data.Models.ApiKey()
                {
                    Flags          = AuthorizeApiKey.Authentication | AuthorizeApiKey.Registration | AuthorizeApiKey.Standard,
                    Description    = "[WIKILIBS_SUPER_DEV_API_KEY]",
                    ExpirationDate = DateTime.MaxValue,
                    UseNum         = -1
                }).Wait();
                manager._logger.LogInformation("A development API Key has been generated");
            }
            var key = manager._context.ApiKeys.FirstOrDefault(x => x.Description == "[WIKILIBS_SUPER_DEV_API_KEY]");
            manager._logger.LogWarning("Development API Key : " + key.Id);
            manager._logger.LogWarning("This development key is intended for development purposes, it has ALL flags enabled and will never expire");
#else
            if (!manager._context.ApiKeys.Any(x => x.Description == "[DEFAULT] BaseKey"))
            {
                manager.ApiKeyManager.PostAsync(new Data.Models.ApiKey()
                {
                    Flags          = AuthorizeApiKey.Authentication | AuthorizeApiKey.Registration,
                    Description    = "[DEFAULT] BaseKey",
                    ExpirationDate = DateTime.MaxValue,
                    UseNum         = -1
                }).Wait();
                manager._logger.LogInformation("A base key has been created, it only supports authentication and registration");
            }
            var key = manager._context.ApiKeys.FirstOrDefault(x => x.Description == "[DEFAULT] BaseKey");
            if (key != null)
            {
                manager._logger.LogWarning("Base Key is : " + key.Id);
                manager._logger.LogWarning("We recommend deleting the base key as soon as possible");
            }
#endif
            if (!manager._context.Groups.Any(x => x.Name == "Default"))
            {
                var g = new Data.Models.Group()
                {
                    Name = "Default"
                };
                manager.GroupManager.PostAsync(g).Wait();
            }
            if (!manager._context.Groups.Any(x => x.Name == "Admin"))
            {
                var g = new Data.Models.Group()
                {
                    Name = "Admin"
                };
                g.Permissions.Add(new Data.Models.Permission()
                {
                    Group = g,
                    Perm  = "*"
                });
                manager.GroupManager.PostAsync(g).Wait();
            }
        }
Beispiel #5
0
        public static Data.Models.Group MapGroup(Group group)
        {
            Data.Models.Group groupToAdd = new Data.Models.Group();
            groupToAdd.Id             = group.Id;
            groupToAdd.Name           = group.Name;
            groupToAdd.AvailableSlots = group.AvailableSlots;

            return(groupToAdd);
        }
        public static Data.Models.Group MapGroup(Group group)
        {
            Data.Models.Group _group = new Data.Models.Group
            {
                id             = group.id,
                name           = group.name,
                availableSlots = group.availableSlots
            };

            return(_group);
        }
Beispiel #7
0
        public async Task UpdateGroup_MissingName_BadRequest(string name)
        {
            // Arrange
            Data.Models.Group randomGroup = null;
            ServiceProvider.ExecuteWithDbScope(db => randomGroup = SeedHelper.GetRandomGroup(db));
            var dto = Mapper.Map <GroupDto>(randomGroup);

            dto.Name = name;

            // Act
            using var response = await Client.PutAsJsonAsync("/api/groups", dto);

            // Assert
            response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
        }
        public async Task CreateGroup_NameAlreadyExists_BadRequest()
        {
            // Arrange
            Data.Models.Group randomGroup = null;
            ServiceProvider.ExecuteWithDbScope(db => randomGroup = SeedHelper.GetRandomGroup(db));
            var dto = GetGroupDto();

            dto.Name = randomGroup.Name;

            // Act
            using var response = await Client.PostAsJsonAsync("/api/groups", dto);

            // Assert
            response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
        }
Beispiel #9
0
        public async Task UpdateGroup_NameTooLong_BadRequest()
        {
            // Arrange
            Data.Models.Group randomGroup = null;
            ServiceProvider.ExecuteWithDbScope(db => randomGroup = SeedHelper.GetRandomGroup(db));
            var dto = Mapper.Map <GroupDto>(randomGroup);

            dto.Name = RandomFactory.GetAlphanumericString(Constants.MaximumLengths.StringColumn + 1);

            // Act
            using var response = await Client.PutAsJsonAsync("/api/groups", dto);

            // Assert
            response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
        }
Beispiel #10
0
        public async Task UpdateGroup_IdDoesNotExist_NotFound(int id)
        {
            // Arrange
            Data.Models.Group randomGroup = null;
            ServiceProvider.ExecuteWithDbScope(db =>
            {
                randomGroup = SeedHelper.GetRandomGroup(db);
            });
            var dto = Mapper.Map <GroupDto>(randomGroup);

            dto.Id = id;

            // Act
            var response = await Client.PutAsJsonAsync("/api/groups", dto);

            // Assert
            response.StatusCode.Should().Be(HttpStatusCode.NotFound);
        }
Beispiel #11
0
        public async Task UpdateGroup_IdDoesNotExist_NotFound(int id)
        {
            // Arrange
            Data.Models.Group randomGroup = null;
            ServiceProvider.ExecuteWithDbScope(db => randomGroup = SeedHelper.GetRandomGroup(db));
            var dto = Mapper.Map <GroupDto>(randomGroup);

            dto.Id = id;

            // Act
            // FIXME: hitting an unknown content stream exception, using workaround - https://stackoverflow.com/a/65532357/1448448
            //using var response = await Client.PutAsJsonAsync("/api/groups", dto);
            using var response = await Client.SendAsync(new HttpRequestMessage ()
            {
                Method     = HttpMethod.Put,
                RequestUri = new Uri($"{Client.BaseAddress}/api/groups"),
                Content    = new ObjectContent(typeof(GroupDto), dto, new JsonMediaTypeFormatter(), "application/json")
            }, HttpCompletionOption.ResponseHeadersRead);

            // Assert
            response.StatusCode.Should().Be(HttpStatusCode.NotFound);
        }
Beispiel #12
0
        public async Task UpdateGroup_NameAlreadyExists_BadRequest()
        {
            // Arrange
            Data.Models.Group randomGroup    = null;
            Data.Models.Group differentGroup = null;
            ServiceProvider.ExecuteWithDbScope(async db =>
            {
                randomGroup    = SeedHelper.GetRandomGroup(db);
                differentGroup = await db.Groups
                                 .Where(x => x.Id != randomGroup.Id)
                                 .OrderBy(_ => Guid.NewGuid())
                                 .FirstAsync();
            });
            var dto = Mapper.Map <GroupDto>(randomGroup);

            dto.Name = differentGroup.Name;

            // Act
            using var response = await Client.PutAsJsonAsync("/api/groups", dto);

            // Assert
            response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
        }
Beispiel #13
0
        public static Data.Context CreateFakeDB(SqliteConnection con)
        {
            var ctx = new Data.Context(new DbContextOptionsBuilder().UseSqlite(con).UseLazyLoadingProxies().Options);

            ctx.Database.EnsureCreated();
            ctx.SaveChanges();
            ctx.Add(new Data.Models.Group()
            {
                Name = "Default"
            });
            var admin = new Data.Models.Group()
            {
                Name = "Admin"
            };

            admin.Permissions.Add(new Data.Models.Permission()
            {
                Group = admin,
                Perm  = "*"
            });
            ctx.Add(admin);
            ctx.SaveChanges();
            return(ctx);
        }
Beispiel #14
0
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                return;
            }
            string oldDbConnect = args[0];
            string newDbConnect = args[1];
            var    newctx       = new Data.Context(new DbContextOptionsBuilder().UseLazyLoadingProxies().UseSqlServer(newDbConnect).Options);
            var    oldctx       = new DB.Context(new DbContextOptionsBuilder <DB.Context>().UseMySql(oldDbConnect).Options);

            foreach (var grp in oldctx.Groups)
            {
                var newGrp = new Data.Models.Group()
                {
                    Name = grp.Name
                };
                foreach (var perm in oldctx.Permissions.Where(o => o.Group == grp.Name))
                {
                    var newPerm = new Data.Models.Permission()
                    {
                        Group = newGrp,
                        Perm  = perm.Perm
                    };
                    newGrp.Permissions.Add(newPerm);
                }
                newctx.Groups.Add(newGrp);
            }
            newctx.SaveChanges();
            foreach (var usr in oldctx.Users)
            {
                var newUsr = new Data.Models.User()
                {
                    Id               = usr.UUID,
                    FirstName        = usr.FirstName,
                    LastName         = usr.LastName,
                    Email            = usr.EMail,
                    Private          = usr.ShowEmail,
                    ProfileMsg       = usr.ProfileMsg,
                    Points           = usr.Points,
                    Pseudo           = usr.Pseudo,
                    Group            = newctx.Groups.Where(g => g.Name == usr.Group).First(),
                    Pass             = SHA512(usr.Pass),
                    RegistrationDate = usr.Date
                };
                newctx.Users.Add(newUsr);
            }
            newctx.SaveChanges();
            foreach (var sym in oldctx.Symbols)
            {
                var newSym = new Symbol()
                {
                    Path                 = sym.Path,
                    CreationDate         = sym.Date,
                    LastModificationDate = DateTime.UtcNow,
                    User                 = newctx.Users.Where(u => u.Id == sym.UserID).FirstOrDefault()
                };
                if (newctx.SymbolTypes.Any(e => e.Name == sym.Type))
                {
                    newSym.Type = newctx.SymbolTypes.Where(e => e.Name == sym.Type).FirstOrDefault();
                }
                else
                {
                    newSym.Type = new Data.Models.Symbols.Type()
                    {
                        Name = sym.Type
                    }
                };
                foreach (var proto in JsonConvert.DeserializeObject <API.Entities.Symbol.Prototype[]>(sym.Prototypes))
                {
                    var newProto = new Data.Models.Symbols.Prototype()
                    {
                        Description = proto.Description,
                        Symbol      = newSym,
                        Data        = proto.Proto
                    };
                    foreach (var param in proto.Parameters)
                    {
                        var newParam = new Data.Models.Symbols.PrototypeParam()
                        {
                            Description = param.Description,
                            Data        = param.Proto,
                            SymbolRef   = param.Path != null ? new PrototypeParamSymbolRef()
                            {
                                RefPath = param.Path
                            } : null,
                            Prototype = newProto
                        };
                        newProto.Parameters.Add(newParam);
                    }
                    newSym.Prototypes.Add(newProto);
                }
                foreach (var symref in JsonConvert.DeserializeObject <string[]>(sym.Symbols))
                {
                    var newSymRef = new Data.Models.Symbols.SymbolRef()
                    {
                        RefPath = symref,
                        Symbol  = newSym
                    };
                    newSym.Symbols.Add(newSymRef);
                }
                newctx.Symbols.Add(newSym);
            }
            newctx.SaveChanges();
        }
    }
Beispiel #15
0
 public Group DeleteGroup(Group group)
 {
     Data.Models.Group groupToDelete = DTOMappers.MapGroup(group);
     _dbContext.DeleteGroup(groupToDelete);
     return(group);
 }
Beispiel #16
0
 public Group UpdateGroup(Group group)
 {
     Data.Models.Group groupToUpdate = DTOMappers.MapGroup(group);
     _dbContext.UpdateGroup(groupToUpdate);
     return(group);
 }
 public async Task Add(Data.Models.Group group)
 {
     _context.Add(group);
     await _context.SaveChangesAsync();
 }