Exemplo n.º 1
0
        public async Task <Result <string> > Create(BlobModel item)
        {
            bool   ok      = false;
            string message = "";

            try
            {
                item.id = Guid.NewGuid().ToString();
                UpdateMetadata(item, true);
                var tenatId = new PartitionKey(_partitionId + "_" + _userInfo.UserId);
                await RepositoryContainer.CreateItemAsync <BlobModel>(item, tenatId);

                message = item.id;

                ok = true;
            }
            catch (CosmosException ex)
            {
                message = ex.Message;
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }

            return(_result.Create <string>(ok, message, message));
        }
Exemplo n.º 2
0
        private Result<bool> validAdmin(HttpRequestMessage req, HttpRequest request, List<string> scopes = null, List<string> tenants = null)
        {
            var resultAuth = validAuthorized(req, request, scopes, tenants);
            if (!resultAuth.Success)
            {
                return _result.Create<bool>(false, resultAuth.Message, false);
            }

            return _result.Create<bool>(true, "", true);
        }
Exemplo n.º 3
0
        public async Task <Result <SocialModel> > GoogleValidateToken(dynamic data)
        {
            SocialModel model;

            try
            {
                var valid = true;

                string token = data.tokenId;
                token = token.Replace("{", string.Empty);
                token = token.Replace("}", string.Empty);
                Payload payload = await ValidateAsync(token, new ValidationSettings
                {
                    Audience = new[] { _settings.GoogleClientId }
                });

                if (!payload.Audience.Equals(_settings.GoogleClientId))
                {
                    valid = false;
                }
                if (!payload.Issuer.Equals(_settings.GoogleISSUER) && !payload.Issuer.Equals("https://" + _settings.GoogleISSUER))
                {
                    valid = false;
                }
                if (payload.ExpirationTimeSeconds == null)
                {
                    valid = false;
                }
                else
                {
                    DateTime now        = DateTime.Now.ToUniversalTime();
                    DateTime expiration = DateTimeOffset.FromUnixTimeSeconds((long)payload.ExpirationTimeSeconds).DateTime;
                    if (now > expiration)
                    {
                        valid = false;
                    }
                }

                if (!valid)
                {
                    return(_result.Create <SocialModel>(false, _errors.NotAuthorized, null));
                }

                model         = new SocialModel();
                model.Email   = payload.Email;
                model.Name    = payload.Name;
                model.Picture = payload.Picture;
            }
            catch (Exception)
            {
                return(_result.Create <SocialModel>(false, _errors.NotAuthorized, null));
            }

            return(_result.Create(true, "", model));
        }
Exemplo n.º 4
0
        public Result <ClaimsPrincipal> ValidateTokenAsync(HttpRequestHeaders headers, IPAddress ipAddress)
        {
            var flag  = false;
            var token = "";

            foreach (var item in headers.GetValues("Cookie"))
            {
                var cookies = item.Split(",");
                for (var x = 0; x < cookies.Length; x++)
                {
                    var idx   = cookies[x].IndexOf("=");
                    var name  = cookies[x].Substring(0, idx);
                    var value = cookies[x].Substring(idx + 1, cookies[x].Length - (idx + 1));
                    if (name == _settings.CookieToken)
                    {
                        flag  = true;
                        token = value;
                        break;
                    }
                }
            }

            if (!flag)
            {
                return(_result.Create <ClaimsPrincipal>(false, _errors.NotAuthorized, null));
            }

            try
            {
                principal = _tokens.ValidateToken(token);
            }
            catch (SecurityTokenException ex)
            {
                if (ex.Message.Contains("Lifetime validation failed"))
                {
                    return(_result.Create <ClaimsPrincipal>(false, _errors.SecurityTokenExpired, null));
                }
                else
                {
                    return(_result.Create <ClaimsPrincipal>(false, _errors.NotAuthorized, null));
                }
            }
            catch (Exception)
            {
                return(_result.Create <ClaimsPrincipal>(false, _errors.NotAuthorized, null));
            }

            if (principal == null)
            {
                return(_result.Create <ClaimsPrincipal>(false, _errors.NotAuthorized, null));
            }

            return(_result.Create(true, "", principal));
        }
Exemplo n.º 5
0
        public async Task<Result<UserPrivateDataModel>> Login(string email)
        {
            bool ok = false;
            string message = "";
            UserPrivateDataModel model = null;

            try
            {
                var queryOptions = new QueryRequestOptions
                {
                    PartitionKey = new PartitionKey(_partitionId),
                    MaxItemCount = 1
                };
                
                var query = $"select * from d where d.Email = '{email}'";
                using (FeedIterator<UserPrivateDataModel> feedIterator = RepositoryContainer.GetItemQueryIterator<UserPrivateDataModel>(
                    query,
                    null,
                    queryOptions))
                {
                    while (feedIterator.HasMoreResults)
                    {
                        foreach (var item in await feedIterator.ReadNextAsync())
                        {
                            model = item;
                            break;
                        }
                    }
                }

                if (model == null)
                {
                    message = _errors.NotFound;
                }
                else
                {
                    ok = true;
                }
            }
            catch (CosmosException ex)
            {
                message = ex.Message;
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }

            return _result.Create(ok, message, model);
        }
        public async Task <Result <LoginDto> > Login(string email, string password, HttpRequest request)
        {
            var result = await _services.Login(email);

            if (!result.Success)
            {
                return(_result.Create <LoginDto>(false, result.Message, null));
            }

            if (result.Value.Block && DateTime.UtcNow < result.Value.ExpirationBlock)
            {
                return(_result.Create <LoginDto>(false, _errors.Block + " " + result.Value.ExpirationBlock.ToString("s"), null));
            }
            else
            {
                var secret = _crypto.GetStringSha256Hash(email + password + _settings.SecretKey);
                if (result.Value.Password != secret)
                {
                    result.Value.TryCounter++;
                    if (result.Value.TryCounter == 3)
                    {
                        DateTime expire = DateTime.UtcNow.AddSeconds(_settingsTokens.ExpiredTimeInSecondsToUserLocked);
                        result.Value.Block           = true;
                        result.Value.ExpirationBlock = expire;

                        if (_settings.RedisCacheSecurity)
                        {
                            var tokens = await _redisCache.GetSringValue(result.Value.id);

                            if (!String.IsNullOrEmpty(tokens))
                            {
                                var modelRedis = JsonConvert.DeserializeObject <RedisSecurityModel>(tokens);
                                modelRedis.Block = true;

                                var jsonString = JsonConvert.SerializeObject(modelRedis);
                                await _redisCache.SetStringValue(result.Value.id, jsonString);
                            }
                        }
                    }
                    await _services.Update(result.Value);

                    return(_result.Create <LoginDto>(false, _errors.NotAuthorized, null));
                }
                else
                {
                    result.Value.Block      = false;
                    result.Value.TryCounter = 0;
                    await _services.Update(result.Value);

                    if (_settings.RedisCacheSecurity)
                    {
                        var tokens = await _redisCache.GetSringValue(result.Value.id);

                        if (!String.IsNullOrEmpty(tokens))
                        {
                            var modelRedis = JsonConvert.DeserializeObject <RedisSecurityModel>(tokens);
                            modelRedis.Scopes     = result.Value.Scopes;
                            modelRedis.Scopes     = result.Value.Tenants;
                            modelRedis.ValidEmail = result.Value.ValidEmail;
                            modelRedis.Block      = false;

                            var jsonString = JsonConvert.SerializeObject(modelRedis);
                            await _redisCache.SetStringValue(result.Value.id, jsonString);
                        }
                    }
                }
            }

            var dataResult = GetToken(result.Value);

            var login = EndToken(request, _settingsTokens.CookieToken, _settingsSecrets.CookieTokenPath, dataResult.Value);

            return(_result.Create(true, "", login));
        }
Exemplo n.º 7
0
        public async Task <Result <TokenDtoOutput> > GenerateToken(string permissionsStorage, int size, int limit,
                                                                   SharedAccessBlobPermissions permissions, string blobName)
        {
            var storageAccount           = CloudStorageAccount.Parse(_settings.StorageAccountConnection);
            var blobClient               = storageAccount.CreateCloudBlobClient();
            var containerName            = _userInfo.UserId;
            CloudBlobContainer container = blobClient.GetContainerReference(containerName);

            await container.CreateIfNotExistsAsync();

            if (permissionsStorage == "Write")
            {
                long fileSize = size;
                BlobContinuationToken continuationToken = null;
                CloudBlob             blob;
                var segmentSize = 100;
                do
                {
                    BlobResultSegment resultSegment = await container.ListBlobsSegmentedAsync(string.Empty,
                                                                                              true, BlobListingDetails.Metadata, segmentSize, continuationToken, null, null);

                    foreach (var blobItem in resultSegment.Results)
                    {
                        blob = (CloudBlob)blobItem;

                        fileSize += blob.Properties.Length;
                        if (limit <= fileSize)
                        {
                            return(_result.Create <TokenDtoOutput>(false, "Upgrade", null));
                        }
                    }

                    continuationToken = resultSegment.ContinuationToken;
                } while (continuationToken != null);
            }

            var sasToken = GetBlobSasToken(container, blobName, permissions);

            /*
             * var sasToken =
             *  data.blobName != null ?
             *      GetBlobSasToken(container, data.blobName.ToString(), permissions) :
             *      GetContainerSasToken(container, permissions);
             */

            var uri = "";

            if (permissionsStorage == "Read")
            {
                uri = container.Uri + "/" + blobName + sasToken;
            }
            if (permissionsStorage == "Delete")
            {
                uri = storageAccount.BlobEndpoint.AbsoluteUri + sasToken;
            }
            if (permissionsStorage == "Write")
            {
                uri = storageAccount.BlobEndpoint.AbsoluteUri + sasToken;
            }

            var tokenModel = new TokenDtoOutput
            {
                Container  = containerName,
                BlobName   = blobName,
                Token      = sasToken,
                Permission = permissionsStorage,
                Uri        = uri
            };

            return(_result.Create <TokenDtoOutput>(true, "", tokenModel));
        }