/// <summary>
        /// Given a <see cref="IHubIncomingInvokerContext"/>, validate all the passed in parameters to determine if they are valid to invoke the <see cref="IHub"/> method.
        /// It checks FluentValidation validators
        /// </summary>
        /// <param name="hubIncomingInvokerContext">An <see cref="IHubIncomingInvokerContext"/> providing details regarding the <see cref="IHub"/> method invocation</param>
        /// <returns>List of invalid fields</returns>
        public IEnumerable <String> ValidateHubMethodInvocation(IHubIncomingInvokerContext hubIncomingInvokerContext)
        {
            var errors = new List <String>();

            for (var i = 0; i < hubIncomingInvokerContext.Args.Count; i++)
            {
                var arg = hubIncomingInvokerContext.Args[i];

                var validatorInstance = FluentValidationHelper.GetValidator(arg);
                if (validatorInstance != null)
                {
                    var validationResult = validatorInstance.Validate(arg);
                    if (!validationResult.IsValid)
                    {
                        var paramName = hubIncomingInvokerContext.MethodDescriptor.Parameters[i].Name;
                        errors.AddRange(validationResult.Errors.Select(error => $"{paramName}.{error.PropertyName}"));
                    }
                }
            }

            return(errors);
        }
Пример #2
0
        public CommonApiResponse <User> Put(UserUpdateView userUpdateView)
        {
            jwt = ViewBag.Jwt;
            User user = _userService.GetById(jwt.UserId, userUpdateView.Id);

            if (user == null)
            {
                return(CommonApiResponse <User> .Create(Response, System.Net.HttpStatusCode.Conflict, false, null, "No members found."));
            }

            user.Email   = userUpdateView.Email;
            user.Name    = userUpdateView.Name;
            user.SurName = userUpdateView.SurName;
            user.Extra1  = userUpdateView.Extra1;
            user.Extra2  = userUpdateView.Extra2;

            bool result = _userService.Update(user);

            if (!result)
            {
                return(CommonApiResponse <User> .Create(Response, System.Net.HttpStatusCode.OK, false, null, FluentValidationHelper.GenerateErrorList("An error occurred.")));
            }

            //return CommonApiResponse<User>.Create(Response, System.Net.HttpStatusCode.OK, true, user, null);
            return(CommonApiResponse <User> .Create(Response, System.Net.HttpStatusCode.OK, true, user, null));
        }
        public CommonApiResponse <Permission> Put(PermissionCrudView permissionView)
        {
            jwt = ViewBag.Jwt;
            Permission permission = new Permission();

            permission.Id          = permissionView.Id;
            permission.UserId      = jwt.UserId;
            permission.Name        = permissionView.Name;
            permission.Description = permissionView.Description;

            bool result = _permissionService.Update(permission);

            if (result)
            {
                return(CommonApiResponse <Permission> .Create(Response, System.Net.HttpStatusCode.OK, true, permission, null));
            }

            return(CommonApiResponse <Permission> .Create(Response, System.Net.HttpStatusCode.OK, false, null, FluentValidationHelper.GenerateErrorList("An error occurred.")));
        }
Пример #4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            string connectionString = Configuration.GetConnectionString("DataBase");

            // Injentando a factory na aplicação
            services.AddSingleton <ISessionFactory>(factory => { return(new NHibernateSessionFactory().CreateFactoryWeb(connectionString)); });

            // Injetando a sessão da factory.
            services.AddScoped <NHibernate.ISession>(factory => factory
                                                     .GetServices <ISessionFactory>().First()
                                                     .OpenSession());

            services.AddScoped <IServiceContext, ServiceContext>();
            services.AddScoped <IUnitOfWork, UnitOfWork>();
            services.AddSingleton <contexto.IHttpContextAccessor, contexto.HttpContextAccessor>();
            services.AddSingleton <IUserHelper, UserHelper>();
            services.Configure <UploadSettingsModel>(Configuration.GetSection("UploadSettings"));

            var appSettingsSection = Configuration.GetSection("AppSettings");

            services.Configure <AppSettingsModel>(appSettingsSection);

            // Injetando os comandos
            // Usuário
            services.AddScoped <ICommandHandler <CadastrarUsuarioCommand>, CadastrarUsuario>();
            services.AddScoped <ICommandHandler <AtualizarDescritivoUsuarioCommand>, AtualizarDescritivoUsuario>();
            services.AddScoped <ICommandHandler <AtualizarUsernameUsuarioCommand>, AtualizarUsernameUsuario>();
            services.AddScoped <ICommandHandler <AtualizarEmailUsuarioCommand>, AtualizarEmailUsuario>();
            services.AddScoped <ICommandHandler <AtualizarFotoUsuarioCommand>, AtualizarFotoUsuario>();
            services.AddScoped <ICommandHandler <AutenticarUsuarioCommand>, AutenticarUsuario>();
            services.AddScoped <ICommandHandler <AtualizarSenhaUsuarioCommand>, AtualizarSenhaUsuario>();
            services.AddScoped <ICommandHandler <AtualizarSenhaUsuarioCommand>, AtualizarSenhaUsuario>();
            services.AddScoped <ICommandHandler <InativarUsuarioCommand>, InativarUsuario>();
            services.AddScoped <ICommandHandler <SeguirUsuarioCommand>, SeguirUsuario>();
            services.AddScoped <ICommandHandler <PararSeguirUsuarioCommand>, PararSeguirUsuario>();

            // Opinião
            services.AddScoped <ICommandHandler <ConcordarNoticiaCommand>, ConcordarNoticia>();
            services.AddScoped <ICommandHandler <DiscordarNoticiaCommand>, DiscordarNoticia>();

            // Publicação
            services.AddScoped <ICommandHandler <CadastrarPublicacaoCommand>, CadastrarPublicacao>();
            services.AddScoped <ICommandHandler <InativarPublicacaoCommand>, InativarPublicacao>();
            services.AddScoped <ICommandHandler <ComentarPublicacaoCommand>, ComentarPublicacao>();
            services.AddScoped <ICommandHandler <RecompartilharPublicacaoCommand>, RecompartilharPublicacao>();
            services.AddScoped <ICommandHandler <UpvotePublicacaoCommand>, UpvotePublicacao>();
            services.AddScoped <ICommandHandler <DownvotePublicacaoCommand>, DownvotePublicacao>();

            // Injetando os QueryObjects
            services.AddScoped <IQueryObject <UsuarioQuery>, UsuarioQuery>();
            services.AddScoped <IQueryObject <NoticiaQuery>, NoticiaQuery>();
            services.AddScoped <IQueryObject <PublicacaoQuery>, PublicacaoQuery>();
            services.AddScoped <IQueryObject <TituloUsuarioQuery>, TituloUsuarioQuery>();
            services.AddScoped <IQueryObject <TituloNoticiaQuery>, TituloNoticiaQuery>();

            // Injetando os repositórios
            services.AddScoped <ILogTransacaoRepository, LogTransacaoRepository>();
            services.AddScoped <IUsuarioRepository, UsuarioRepository>();
            services.AddScoped <IOpiniaoRepository, OpiniaoRepository>();
            services.AddScoped <IPublicacaoRepository, PublicacaoRepository>();
            services.AddScoped <IPublicacaoUpvoteRepository, PublicacaoUpvoteRepository>();
            services.AddScoped <IPublicacaoDownvoteRepository, PublicacaoDownvoteRepository>();
            services.AddScoped <ITituloUsuarioRepository, TituloUsuarioRepository>();
            services.AddScoped <ISeguidorUsuarioRepository, SeguidorUsuarioRepository>();

            services.AddSingleton <Appinion.Api.Helper.Quartz>();

            services.AddTransient <IJobFactory, JobFactory>(
                (provider) =>
            {
                return(new JobFactory(provider));
            });
            services.AddTransient <TituloUsuarioComMaisPublicacoesJob>();
            services.AddTransient <TituloUsuarioComMaisUpvotesJob>();
            services.AddTransient <TituloUsuarioComMaisDownvotesJob>();

            services.AddTransient <TituloNoticiaMaisConcordada>();
            services.AddTransient <TituloNoticiaMaisDiscordada>();

            // Inicializando a Autorização JWT
            var appSettings = appSettingsSection.Get <AppSettingsModel>();
            var key         = Encoding.ASCII.GetBytes(appSettings.Secret);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.Events = new JwtBearerEvents
                {
                    OnTokenValidated = context =>
                    {
                        var usuarioRepository = context.HttpContext.RequestServices.GetRequiredService <IUsuarioRepository>();
                        var usuarioId         = int.Parse(context.Principal.Identity.Name);
                        var user = usuarioRepository.Find(usuarioId);
                        if (user == null)
                        {
                            context.Fail("Não Autorizado");
                        }
                        return(Task.CompletedTask);
                    }
                };
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            // Inicializando o Automapper
            InitializeMapper();

            // Inicializando os validadores dos comandos
            FluentValidationHelper.InitializeValidators(services);

            services.AddMvc(options =>
            {
                options.Filters.Add(new SessionFilter());
                options.Filters.Add(new CustomActionFilter());
            }).AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver())
            .AddJsonOptions(options => options.SerializerSettings.MaxDepth           = 2)
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
Пример #5
0
        public CommonApiResponse <string> Delete(Guid rolePermissionId)
        {
            jwt = ViewBag.Jwt;
            bool result = _rolePermissionService.Delete(jwt.UserId, rolePermissionId);

            if (result)
            {
                return(CommonApiResponse <string> .Create(Response, System.Net.HttpStatusCode.OK, true, "İşlem başarılı", null));
            }

            return(CommonApiResponse <string> .Create(Response, System.Net.HttpStatusCode.OK, false, null, FluentValidationHelper.GenerateErrorList("An error occurred.")));
        }
Пример #6
0
        public CommonApiResponse <dynamic> Post(Guid roleId, string _permissionId)
        {
            jwt = ViewBag.Jwt;
            Guid           permissionId   = Guid.Parse(_permissionId);
            RolePermission rolePermission = new RolePermission();

            rolePermission.UserId       = jwt.UserId;
            rolePermission.PermissionId = permissionId;
            rolePermission.RoleId       = roleId;

            bool   result = false;
            string error  = "";

            Guid insertId = _rolePermissionService.Save(rolePermission);

            result = Guid.TryParse(insertId.ToString(), out insertId);
            if (result)
            {
                rolePermission.Id = insertId;
                var result1 = _rolePermissionService.GetByUserIdAndIdWithJoinPermission(jwt.UserId, roleId, rolePermission.Id);

                return(CommonApiResponse <dynamic> .Create(Response, System.Net.HttpStatusCode.OK, true, result1, null));
            }

            return(CommonApiResponse <dynamic> .Create(Response, System.Net.HttpStatusCode.BadRequest, false, null, FluentValidationHelper.GenerateErrorList(error)));
        }
Пример #7
0
        public CommonApiResponse <Role> Put(RoleUpdateView roleUpdateView)
        {
            jwt = ViewBag.Jwt;
            Role role = _roleService.GetById(jwt.UserId, roleUpdateView.Id);

            if (role == null)
            {
                return(CommonApiResponse <Role> .Create(Response, System.Net.HttpStatusCode.OK, false, null, FluentValidationHelper.GenerateErrorList("Role not found.")));
            }

            role.Name        = roleUpdateView.Name;
            role.Description = roleUpdateView.Description;
            bool result = _roleService.Update(role);

            if (result)
            {
                return(CommonApiResponse <Role> .Create(Response, System.Net.HttpStatusCode.OK, true, role, null));
            }
            else
            {
                return(CommonApiResponse <Role> .Create(Response, System.Net.HttpStatusCode.OK, false, null, FluentValidationHelper.GenerateErrorList("An error occurred.")));
            }
        }
Пример #8
0
        public CommonApiResponse <Role> Post(RoleRegisterView roleRegisterView)
        {
            jwt = ViewBag.Jwt;
            Role role = new Role();

            role.Name        = roleRegisterView.Name;
            role.UserId      = jwt.UserId;
            role.Description = roleRegisterView.Description;
            role.StatusId    = 2;//Active

            Guid insertId = _roleService.Save(role);
            bool result   = Guid.TryParse(insertId.ToString(), out insertId);

            if (result)
            {
                return(CommonApiResponse <Role> .Create(Response, System.Net.HttpStatusCode.OK, true, role, null));
            }
            else
            {
                return(CommonApiResponse <Role> .Create(Response, System.Net.HttpStatusCode.OK, false, new Role(), FluentValidationHelper.GenerateErrorList("An error occurred.")));
            }
        }
Пример #9
0
        public CommonApiResponse <string> Delete(Guid userId, Guid id)
        {
            jwt = ViewBag.Jwt;

            List <UserRole> list = _userRoleService.GetByRoleId(id);

            if (list.Count > 0)
            {
                return(CommonApiResponse <string> .Create(Response, System.Net.HttpStatusCode.InternalServerError, false, null, FluentValidationHelper.GenerateErrorList("This role can not be deleted because it is used.")));
            }

            bool result = _roleService.Delete(id, userId);

            if (result)
            {
                return(CommonApiResponse <string> .Create(Response, System.Net.HttpStatusCode.OK, true, "İşlem başarılı", null));
            }

            return(CommonApiResponse <string> .Create(Response, System.Net.HttpStatusCode.InternalServerError, false, null, FluentValidationHelper.GenerateErrorList("An error occurred.")));
        }