Пример #1
0
 public void ReceiveMessage(object sender, Message message)
 {
     if (message.Key == "点击列表")
     {
         Key = message.Content as KeySecret;
     }
 }
Пример #2
0
        public override void ReceiveMessage(object sender, IMessage e)
        {
            Message message = e as Message;

            if (message?.Key == "点击列表")
            {
                Key = message.Content as KeySecret;
            }
        }
Пример #3
0
        public Task SetKeySecretAsync(KeySecret keySecret)
        {
            ConcurrentDictionary <string, KeySecret> vault = _cache.GetOrAdd(
                key: keySecret.VaultName,
                value: new ConcurrentDictionary <string, KeySecret>(StringComparer.InvariantCultureIgnoreCase));

            vault.TryAdd(key: keySecret.Key, value: keySecret);

            return(Task.CompletedTask);
        }
Пример #4
0
        public Property CtorValuesInjected(string vault, string key, string value)
        {
            Func <bool> rule = () =>
            {
                var ks = new KeySecret(vaultName: vault, key: key, value: value);

                return(ks.VaultName == vault && ks.Key == key && ks.Value == value);
            };

            return(rule.When(vault != null && key != null && value != null));
        }
Пример #5
0
        private async Task SetAsync(Func <string, string> keyFcn, PropertyInfo property, TItem instance)
        {
            string key = keyFcn(property.Name);

            if (property.PropertyType != typeof(string))
            {
                throw new InvalidOperationException("Invalid parameter type.");
            }

            KeySecret keySecret = new KeySecret(key: key, value: (string)property.GetValue(instance));
            await _keySecretProvider.SetKeySecretAsync(keySecret);
        }
Пример #6
0
        protected async Task <string> GetAsync(Func <string, string> keyFcn, PropertyInfo property)
        {
            string key = keyFcn(property.Name);

            if (property.PropertyType != typeof(string))
            {
                throw new InvalidOperationException("Invalid parameter type.");
            }

            KeySecret keySecret = await _keySecretReadOnlyProvider.GetKeySecretAsync(key);

            return(keySecret.Value);
        }
Пример #7
0
        public static async Task <string> GetRefreshTokenUserAndDestroyToken(string encodedToken)
        {
            KeySecret keySecret = DecodeKeyAndSecret(encodedToken);

            var refreshToken = await TableStorageRepository.GetRefreshToken(keySecret.Key, keySecret.Secret);

            if (refreshToken == null)
            {
                return(null);
            }

            TableStorageRepository.DeleteRefreshToken(refreshToken);

            return(keySecret.Key);
        }
Пример #8
0
        protected async Task <IEnumerable <string> > GetListAsync(
            Func <string, string> keyFcn,
            PropertyInfo property)
        {
            string key = keyFcn(property.Name);

            if (property.PropertyType != typeof(List <string>))
            {
                throw new InvalidOperationException("Invalid parameter type.");
            }

            KeySecret keySecret = await _keySecretReadOnlyProvider.GetKeySecretAsync(key);

            List <string> valueAsList = keySecret.Value.Split(" ").ToList();

            return(valueAsList);
        }
Пример #9
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "delete", Route = "track/{trackId}/post/{postId}")] HttpRequest req, string trackId, string postId, TraceWriter log)
        {
            try
            {
                KeySecret keySecret = AuthRepository.DecodeKeyAndSecret(req.Headers["X-Track-Key"]);

                // validate authKey
                if (!AuthRepository.ValidateSHA256(trackId + keySecret.Key, keySecret.Secret))
                {
                    return(new UnauthorizedResult());
                }

                // get track
                TrackAuth track = await TrackRepository.GetTrack(trackId);

                if (track == null || track.track_key != keySecret.Key)
                {
                    return(new UnauthorizedResult());
                }

                // get post
                Post post = await PostRepository.GetPost(trackId, postId);

                if (post == null || track.RowKey != post.PartitionKey)
                {
                    return(new UnauthorizedResult());
                }

                // delete the post
                TableStorageRepository.AddMessageToQueue("process-delete-post", $"{trackId}.{postId}");

                // return response
                return(new OkResult());
            }
            catch (Exception e)
            {
                log.Info(e.Message);
                return(new UnauthorizedResult());
            }
        }
Пример #10
0
 public override void OnNavigatedTo(object sender, object obj)
 {
     Key = obj as KeySecret;
 }
Пример #11
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "track/{trackId}/post")] HttpRequest req, string trackId, TraceWriter log)
        {
            try
            {
                KeySecret keySecret = AuthRepository.DecodeKeyAndSecret(req.Headers["X-Track-Key"]);
                if (keySecret == null)
                {
                    return(new UnauthorizedResult());
                }

                // validate authKey
                if (!AuthRepository.ValidateSHA256(trackId + keySecret.Key, keySecret.Secret))
                {
                    return(new UnauthorizedResult());
                }

                // get post from req body
                string        requestBody = new StreamReader(req.Body).ReadToEnd();
                PostSubmitDTO post        = JsonConvert.DeserializeObject <PostSubmitDTO>(requestBody);

                // validate post
                PostValidateDTO validatedPost = PostRepository.ValidatePost(post);
                if (validatedPost.invalid_reason != null)
                {
                    return(new BadRequestObjectResult(validatedPost.invalid_reason));
                }

                // get track
                TrackAuth track = await TrackRepository.GetTrack(trackId);

                if (track == null || track.track_key != keySecret.Key)
                {
                    return(new UnauthorizedResult());
                }

                // check rate limit
                if (track.rate_limit_exceeded)
                {
                    return(new ForbidResult());
                }

                // create the post
                validatedPost.post.track_id   = trackId;
                validatedPost.post.track_name = track.name;
                Post newPost = await PostRepository.InsertPost(validatedPost.post);

                // if didn't create return bad response
                if (newPost == null)
                {
                    return(new BadRequestResult());
                }

                // convert to post DTO
                return(new OkObjectResult(new PostQueryDTO()
                {
                    date_created = newPost.date_created,
                    id = newPost.RowKey,
                    summary = newPost.summary,
                    tags = newPost.tags.Split(',').ToList(),
                    title = newPost.title,
                    track_id = newPost.PartitionKey,
                    track_name = newPost.track_name,
                    type = newPost.type,
                    url = newPost.url
                }));
            }
            catch (Exception e)
            {
                log.Info(e.Message);
                return(new UnauthorizedResult());
            }
        }
Пример #12
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "track/{trackId}/posts")] HttpRequest req, string trackId, TraceWriter log)
        {
            try
            {
                // check valid trackId provided
                if (!Tools.IsValidGuid(trackId))
                {
                    return(new UnauthorizedResult());
                }

                // get the track
                TrackAuth track = await TrackRepository.GetTrack(trackId);

                if (track == null)
                {
                    return(new UnauthorizedResult());
                }

                // private track so check keys
                if (track.is_private)
                {
                    string trackKeyHeader = req.Headers["X-Track-Key"];
                    string authToken      = req.Headers["Authorization"];

                    if (authToken != null)
                    {
                        // validate authKey
                        AuthClaim authClaim = AuthRepository.ValidateAuthClaim(authToken);
                        if (authClaim == null)
                        {
                            return(new UnauthorizedResult());
                        }

                        // check track userID matches authClaim userId
                        if (track.PartitionKey != authClaim.user_id)
                        {
                            return(new UnauthorizedResult());
                        }
                    }
                    else if (trackKeyHeader != null)
                    {
                        KeySecret keySecret = AuthRepository.DecodeKeyAndSecret(trackKeyHeader);

                        // validate authKey
                        if (!AuthRepository.ValidateSHA256(trackId + keySecret.Key, keySecret.Secret))
                        {
                            return(new UnauthorizedResult());
                        }

                        // validate track key
                        if (track.track_key != keySecret.Key)
                        {
                            return(new UnauthorizedResult());
                        }
                    }
                    else
                    {
                        return(new UnauthorizedResult());
                    }
                }

                // get query object from query params
                PostQuery query = Tools.GetQueryFromQueryParams(trackId, req.Query["tags"], req.Query["continuation"]);

                PostReturnObject posts = query.tags.Count > 0 ? await PostRepository.QueryPosts(query) : await PostRepository.GetPosts(query);

                return(new OkObjectResult(posts));
            }
            catch (Exception e)
            {
                log.Info(e.Message);
                return(new BadRequestObjectResult(e.Message));
            }
        }
Пример #13
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "track/{trackId}")] HttpRequest req, string trackId, TraceWriter log)
        {
            try
            {
                // check postId and trackId provided
                if (!Tools.IsValidGuid(trackId))
                {
                    return(new UnauthorizedResult());
                }

                // get the track
                TrackAuth track = await TrackRepository.GetTrack(trackId);

                if (track == null)
                {
                    return(new UnauthorizedResult());
                }

                // is private
                if (track.is_private)
                {
                    string trackKeyHeader = req.Headers["X-Track-Key"];
                    string authToken      = req.Headers["Authorization"];

                    if (authToken != null)
                    {
                        // validate authKey
                        AuthClaim authClaim = AuthRepository.ValidateAuthClaim(authToken);
                        if (authClaim == null)
                        {
                            return(new UnauthorizedResult());
                        }

                        // check track userID matches authClaim userId
                        if (track.PartitionKey != authClaim.user_id)
                        {
                            return(new UnauthorizedResult());
                        }
                    }
                    else if (trackKeyHeader != null)
                    {
                        KeySecret keySecret = AuthRepository.DecodeKeyAndSecret(trackKeyHeader);

                        // validate authKey
                        if (!AuthRepository.ValidateSHA256(trackId + keySecret.Key, keySecret.Secret))
                        {
                            return(new UnauthorizedResult());
                        }

                        // validate track key
                        if (track.track_key != keySecret.Key)
                        {
                            return(new UnauthorizedResult());
                        }
                    }
                    else
                    {
                        return(new UnauthorizedResult());
                    }
                }

                return(new OkObjectResult(new Track(track)));
            }
            catch (Exception e)
            {
                log.Error(e.Message);
                return(new UnauthorizedResult());
            }
        }
Пример #14
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "track/{trackId}/post/{postId}")] HttpRequest req, string trackId, string postId, TraceWriter log)
        {
            try
            {
                // check postId and trackId provided
                if (!Tools.IsValidGuid(trackId))
                {
                    return(new UnauthorizedResult());
                }

                // get the track
                TrackAuth track = await TrackRepository.GetTrack(trackId);

                if (track == null)
                {
                    return(new UnauthorizedResult());
                }

                if (track.is_private)
                {
                    string trackKeyHeader = req.Headers["X-Track-Key"];
                    string authToken      = req.Headers["Authorization"];

                    if (authToken != null)
                    {
                        // validate authKey
                        AuthClaim authClaim = AuthRepository.ValidateAuthClaim(authToken);
                        if (authClaim == null)
                        {
                            return(new UnauthorizedResult());
                        }

                        // check track userID matches authClaim userId
                        if (track.PartitionKey != authClaim.user_id)
                        {
                            return(new UnauthorizedResult());
                        }
                    }
                    else if (trackKeyHeader != null)
                    {
                        KeySecret keySecret = AuthRepository.DecodeKeyAndSecret(trackKeyHeader);

                        // validate authKey
                        if (!AuthRepository.ValidateSHA256(trackId + keySecret.Key, keySecret.Secret))
                        {
                            return(new UnauthorizedResult());
                        }

                        // validate track key
                        if (track.track_key != keySecret.Key)
                        {
                            return(new UnauthorizedResult());
                        }
                    }
                    else
                    {
                        return(new UnauthorizedResult());
                    }
                }

                // get the post
                Post post = await PostRepository.GetPost(trackId, postId);

                if (post == null)
                {
                    return(new UnauthorizedResult());
                }

                // convert to post DTO
                return(new OkObjectResult(new PostDTO()
                {
                    body = post.body,
                    date_created = post.date_created,
                    id = post.RowKey,
                    summary = post.summary,
                    tags = post.tags.Split(',').ToList(),
                    title = post.title,
                    track_id = post.PartitionKey,
                    track_name = post.track_name,
                    type = post.type,
                    url = post.url
                }));
            }
            catch (Exception e)
            {
                log.Info(e.Message);
                return(new UnauthorizedResult());
            }
        }
Пример #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().AddNewtonsoftJson();

            var key = new KeySecret();

            services.Configure <KeySecret>(Configuration.GetSection("KeySecret"));
            Configuration.GetSection("KeySecret").Bind(key);

            services.AddAutoMapper(typeof(Startup));
            services.AddSwaggerGen(x =>
            {
                x.SwaggerDoc("V1", new OpenApiInfo
                {
                    Title = "API VXTEL", Description = "API para consultar planos oferecidos pela VXTEL", Version = "V1"
                });

                x.AddSecurityDefinition("Bearer ", new OpenApiSecurityScheme
                {
                    In           = ParameterLocation.Header,
                    Description  = "Por favor se autenticar",
                    Name         = "Authorization",
                    Type         = SecuritySchemeType.ApiKey,
                    Scheme       = "Bearer",
                    BearerFormat = "JWT"
                });

                x.AddSecurityRequirement(new OpenApiSecurityRequirement {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer "
                            }
                        },
                        new string[] { }
                    }
                });
            });

            var autenticacao = Encoding.ASCII.GetBytes(key.Key);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(autenticacao),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            services.AddScoped <ITabelacaoPrecos, TabelacaoPrecos>();
            services.AddScoped <IPlanosVxTelRepository, PlanosVxTelRepository>();
            services.AddScoped <SqlDataContext, SqlDataContext>();
            services.AddScoped <ICalculaPlano, CalculaPlano>();
            services.AddScoped <TokenService, TokenService>();
            services.AddScoped <ILoginUser, LoginUser>();
            services.AddScoped <IAdministradorRepository, AdministradorRepository>();
            services.AddScoped <IPlanosVxTellApplication, PlanosVxTellApplication>();
        }