teleren/devto huggingface dataset:
Clean Architecture: implementando meu primeiro Use Case
Tags: javascript, beginners, braziliandevs, todayilearned
Published: 2022-05-27 02:41:35

Seguindo o curso que estou usando para aprender sobre Clean Arch a ideia é refatorarmos o projeto de [DDD](https://github.com/Yansb/full-cycle-course/tree/master/domain-driven-design) para aplicar a Clean Architecture


## Implementação

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h32y7tu8dsbb8mp6tptr.png)

De inicio a ideia é já adicionar um pasta de useCase onde vão ficar todos os useCases, então criamos a pasta customer que nesse contexto seria a entidade e a pasta find que é o useCase que vou implementar primeiro para o customer dentro dessa pasta vamos criar o arquivo `find.customer.dto.ts` que vai definir as interfaces do input e output dos dados para esse use case

```js
export interface InputFindCustomerDto {
  id: string;
}

export interface OutputFindCustomerDto {
  id: string;
  name: string;
  address: {
    street: string;
    city: string;
    number: string;
    zip: string;
  }
}
```

E então vamos para a implementação do useCase em si, que vai receber no construtor a interface do repositório de customer, para que ele possa receber qualquer implementação desse repositorio.

```js
export class FindCostumerUseCase{
  constructor(private customerRepository: CustomerRepositoryInterface){}
  
  async execute({id}: InputFindCustomerDto): Promise<OutputFindCustomerDto>{
    const customer = await this.customerRepository.find(id);

    return {
      id: customer.id,
      name: customer.name,
      address: {
        street: customer.address.street,
        number: customer.address.number,
        zip: customer.address.zip,
        city: customer.address.city
      }
    }
  }
```

Nesse caso eu não precisava formatar os dados para retornar no formato do DTO pois por padrão já seria retornado nesse formato, porem quis fazer dessa forma mais por motivos didáticos e me forçar a não esquecer.
Ethernaut系列-Level 14(GatekeeperTwo)
Published: 2022-05-27 02:06:04

## LEVEL 14 （GatekeeperTwo）:
```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

contract GatekeeperTwo {

  address public entrant;

  modifier gateOne() {
    require(msg.sender != tx.origin);
    _;
  }

  modifier gateTwo() {
    uint x;
    assembly { x := extcodesize(caller()) }
    require(x == 0);
    _;
  }

  modifier gateThree(bytes8 _gateKey) {
    require(uint64(bytes8(keccak256(abi.encodePacked(msg.sender)))) ^ uint64(_gateKey) == uint64(0) - 1);
    _;
  }

  function enter(bytes8 _gateKey) public gateOne gateTwo gateThree(_gateKey) returns (bool) {
    entrant = tx.origin;
    return true;
  }
}
```
## 通关要求
  entrant=player

##要点
  1.tx.origin和msg.sender的区别，这个前面有讲
  2.EOA和合约区别，以及extcodesize
  3.位计算
^ 异或 两个位相同为0，相异为1

##解题思路
gateOne:在自己的合约调用其他合约，则tx.origin和msg.sender就会不一样
gateTwo:正常EOA账号的codesize=0,合约不等于0，但有个例外就是在合约的构造器constructor里代用外部合约，这时是codesize为0的，因为还没初始化完合约。
gateThree:位计算，见下面的代码提示

```solidity
        //gateThree:require(uint64(bytes8(keccak256(abi.encodePacked(msg.sender)))) ^ uint64(_gateKey) == uint64(0) - 1);
        //结果再异或下
        uint64 gateKey;
        unchecked {
            gateKey = (uint64(0) - 1) ^
                uint64(bytes8(keccak256(abi.encodePacked(address(this))))); 
        }
        ILevel(_runAddress).enter(bytes8(gateKey));
    }
```
Why Is Broken Access Control OWASP’s #1 Threat?
Tags: security, cybersecurity, zerotrust
Published: 2022-05-26 23:43:32

Do you know the #1 OWASP security risk is broken access control? And the reasons? We had a great conversation with Bill and shared some thoughts here.

https://accelerationeconomy.com/cybersecurity/why-is-broken-access-control-owasps-1-threat/
May 26th, 2022: What did you learn this week?
Tags: discuss, weeklyretro, weeklylearn
Published: 2022-05-26 23:43:25

It's that time of the week again. So wonderful devs, what did you learn this week? It could be programming tips, career advice etc.

![Thor being cocky](https://media.giphy.com/media/12EqthyHl3Auys/giphy.gif)

Feel free to comment with what you learnt and/or reference your TIL post to give it some more exposure.

{%tag todayilearned %}
React Tip
Tags: react, frontend, javascript, webdev
Published: 2022-05-26 23:11:44

💡 React Tip💡

If you have a parent component which stores an array in the state like this:

𝘤𝘰𝘯𝘴𝘵 𝘗𝘢𝘳𝘦𝘯𝘵 = () => {
𝘤𝘰𝘯𝘴𝘵 [𝘶𝘴𝘦𝘳𝘴, 𝘴𝘦𝘵𝘜𝘴𝘦𝘳𝘴] = 𝘶𝘴𝘦𝘚𝘵𝘢𝘵𝘦([]);
𝘳𝘦𝘵𝘶𝘳𝘯 <𝘊𝘩𝘪𝘭𝘥 𝘶𝘴𝘦𝘳𝘴={𝘶𝘴𝘦𝘳𝘴} 𝘴𝘦𝘵𝘜𝘴𝘦𝘳𝘴={𝘴𝘦𝘵𝘜𝘴𝘦𝘳𝘴} />;
}

And for some reason If you are adding new element to the array from the child component like this:

𝘤𝘰𝘯𝘴𝘵 𝘊𝘩𝘪𝘭𝘥 = ({ 𝘶𝘴𝘦𝘳𝘴, 𝘴𝘦𝘵𝘜𝘴𝘦𝘳𝘴 }) => {
𝘤𝘰𝘯𝘴𝘵 𝘩𝘢𝘯𝘥𝘭𝘦𝘈𝘥𝘥 = (𝘶𝘴𝘦𝘳) => {
𝘴𝘦𝘵𝘜𝘴𝘦𝘳𝘴([...𝘶𝘴𝘦𝘳𝘴, 𝘶𝘴𝘦𝘳]);
};
// 𝘴𝘰𝘮𝘦 𝘑𝘚𝘟
};

then instead of passing the extra 𝘂𝘀𝗲𝗿𝘀 prop just to append to the original array state as shown below:

<𝘊𝘩𝘪𝘭𝘥 𝘶𝘴𝘦𝘳𝘴={𝘶𝘴𝘦𝘳𝘴} 𝘴𝘦𝘵𝘜𝘴𝘦𝘳𝘴={𝘴𝘦𝘵𝘜𝘴𝘦𝘳𝘴} />

you can pass only the 𝘀𝗲𝘁𝗨𝘀𝗲𝗿𝘀 as prop to the child component and use the updater syntax of state for adding new user like this:

𝘤𝘰𝘯𝘴𝘵 𝘊𝘩𝘪𝘭𝘥 = ({ 𝘴𝘦𝘵𝘜𝘴𝘦𝘳𝘴 }) => {
𝘤𝘰𝘯𝘴𝘵 𝘩𝘢𝘯𝘥𝘭𝘦𝘈𝘥𝘥 = (𝘶𝘴𝘦𝘳) => {
𝘴𝘦𝘵𝘜𝘴𝘦𝘳𝘴((𝘱𝘳𝘦𝘷) => [...𝘱𝘳𝘦𝘷, 𝘶𝘴𝘦𝘳]);
};
}

Here, the 𝗽𝗿𝗲𝘃 parameter will automatically receive the previous value of users array so you can easily add new element to it.

This will avoid the need of passing extra users prop.

𝗘𝘅𝘁𝗿𝗮 𝗧𝗶𝗽: In 𝘂𝘀𝗲𝗘𝗳𝗳𝗲𝗰𝘁 hook, always try to use the updater syntax using the previous value as shown above so you don't need to add extra variable to dependencies array.


#javascript #reactjs
Day 48: Crazy week
Published: 2022-05-26 22:38:09

Hi!
Thi wee is crazy and is the unexpected one o far including preparations, journey, presentations, taking care of things, coming back home... expected to be back today but It didn't happen so I expect to get back tomorrow. what I can see is that I won't be fully back until Saturday or even Sunday. the project is kinda dead but all these tasks ere very important too. but maybe I may be able to do something about it and save it before it's too late.
we'll see

Signing off...
Review Functions in JavaScript
Published: 2022-05-26 22:37:30

A function is a reusable block of code that groups together a sequence of statements to perform a specific task.

A function declaration :

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0qph5hu1afecgs7kxm8m.png)

A parameter is a named variable inside a function’s block which will be assigned the value of the argument passed in when the function is invoked:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/txz1vxxto8ptjhwa3vm9.png)

To call a function in your code:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w6pokhr3g6fqj9aqbk79.png)

ES6 introduces new ways of handling arbitrary parameters through default parameters which allow us to assign a default value to a parameter in case no argument is passed into the function.

To return a value from a function, we use a return statement.

To define a function using function expressions:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u78bcfkadfsiz5z836wf.png)

To define a function using arrow function notation:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h70hz8or3b5432t6kibz.png)

Function definition can be made concise using concise arrow notation:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n4ru38junia2l3qn7xhi.png)

It’s good to be aware of the differences between function expressions, arrow functions, and function declarations. As you program more in JavaScript, you’ll see a wide variety of how these function types are used.
All you need to know about IF statements
Tags: beginners, python
Published: 2022-05-26 21:37:22

You may be thinking: I already know how to use IF statements in Python.
Yes, you do.
So, why am I writing this?
Well, if you have just started learning Python, or if you have never used it before, here are some tips that may help you:

If you want to test if a variable is True or False, you can just do this:

```
variable1 = True
variable2 = False

if variable1:
   print("The first variable is True")

if not variable2:
   print("The second variable is False")
```

You can do the same thing to test if there is a value assigned to the variable:

```
variable1 = "Some text"
variable2 = 1
variable3 = ""

if variable1:
   print("The first variable has a value assigned to it")

if variable2:
   print("The second variable has a value assigned to it")

if not variable3:
   print("The third variable has not a value assigned to it")
```

To check if a value is inside a list, use this:

```
numbers = ["one", "two", "three", "four", "five"]

if "four" in numbers:
   print("The number four is in the list")
```

Remember: "one" is numbers[0], not numbers[1]. This last one is "two".

Atention: to check if a value is equal to another, you can't use the examples above. Use `x == y`.
Security in Laravel: How to Protect Your App Part 2
Tags: laravel, security, xss
Published: 2022-05-26 21:32:40

## **XSS Attack**

This attack could be divided into two sections. The first one restricts special tags on the server and does not return special tags in the views.

## **Restrict Special Tags in the Server**

You could use different approaches. PHP natively has some methods like strip_tags that only protect against HTML and PHP tags. You can even use a regex or use the PHP native method htmlentities() or filter_var both, although it does not protect completely against all the possible tags. In this case, my best recommendation is to use a specific package to solve this, like 

## **HTML Purifier.**

Does Not Return Special Tags in the Views
If you are working with the Blade template engine, you should take care about how you are printing your data in your template:

```
<p>{{ $user->name }}</p>
```
The double mustaches syntax would protect you against XSS attacks by automatically escaping the tags for you.

```
<p>{!! $user->name !!}</p>
```
On the other hand, this syntax is dangerous. If you do not trust the data that could come, do not use it because the bang-bang syntax could interpret PHP.

## **Using Another PHP Template Engine**

Laravel also provides an escape method that we use on any other template engine like Twig:

```
{{ e($user->name) }}
```

## **Using a Javascript Framework**
Any modern Javascript framework automatically protects us to inject a script. VueJS, for example, has a v-html directive that already protects us against this type of attack.
AI Chatbot
Tags: python, javascript, machinelearning, ai
Published: 2022-05-26 21:26:50

Hey, this is  more of a question, anyone knows the best/to approach way of creating a ai chatbot? In my case, i want to create a bot to chat with people, so not only i have to train him, but build a database/dataset ( the ones online are not what i want/ cant find what i exaactly want ) . Anyone knows how i should proceed? In terms of not only coding language ( python,javascript... ) , but also what libraries to use and how to train the bot/ai!
GraphQL Yoga | Made with Next JS
Published: 2022-05-26 21:24:40

![GraphQL Yoga | Made with Javascript | Next JS](https://res.cloudinary.com/madewithjavascript/image/upload/v1652959994/large_graph_ql_yoga_made_with_next_js_97407d88f3.png "GraphQL Yoga | Made with Javascript | Next JS")


### Fully-featured, simple to set up, performant and extendable GraphQL NodeJS (JavaScript/TypeScript) server

> Leverage the GraphQL ecosystem by being compatible with the existing schema-design (Code/Schema first), HTTP server libraries (Express, Fastify, Next.js, SvelteKit, etc..), and deployment environments (Cloudflare Workers, Deno, AWS Lambda and others..).
> 
> ### GraphQL over HTTP compliant
> Yoga follows the GraphQL over HTTP specification.
> 
> ### Extensible GraphQL Engine powered by Envelop
> Add authentication, caching, error reporting or rate limiting with ease.
> 
> ### GraphQL Subscriptions over HTTP
> Run GraphQL Subscriptions over HTTP instead of WebSockets via Server Sent Events.
> 
> ### Handle file uploads with GraphQL
> Enable file uploads using GraphQL mutations with no additional packages needed.

## Check out more such amazing projects on our website

[Made with Javascript](https://madewithjavascript.club)

## Want us to feature your project

[Submit your Project to Made with Javascript](https://madewithjavascript.club/submit-project)


You can also write to us for any of your queries at:

[Email Made with Javascript](mailto:madewithjavascript@gmail.com)

## Project already shared on our social media handles.

| SocialMedia | SharedLink |
| ----------- | ---------- |
| Twitter | [GraphQL Yoga on Twitter](https://twitter.com/withjavascript/status/1529935522549973009?s=20&t=o-5V1rSZ9571Boka1PZoWQ)
 |
| Medium | [GraphQL Yoga on Medium](https://medium.com/@madewithjavascript/graphql-yoga-made-with-next-js-8e11b2e8e235)
 |
| Facebook | [GraphQL Yoga on Facebook](https://www.facebook.com/madewithjavascript/posts/pfbid02jERbQUHT4gbdNQrp7JZHLrtk5QAWWixwG7vwwyUgSZLHLgDwAAZzbqKZ4qyhRmQ6l)
 |
| Tumblr | [GraphQL Yoga on Tumblr](https://madewithjavascript.tumblr.com/post/685349427543719936/graphql-yoga-made-with-next-js-fully-featured)
 |
| LinkedIn | [GraphQL Yoga on LinkedIn](https://www.linkedin.com/feed/update/urn:li:activity:6935701381240553472)
 |


Filled Under:

 - [Made with Javascript](https://madewithjavascript.club)    
 - [Made with Next JS](https://madewithjavascript.club/categories/next-js)

Make sure to give this post ❤ 50 ❤ hearts, click the 🦄 unicorns 🦄 and follow 👉 @madewithjavascript 👈 for more such awesome showcases. Show you love for the people who have worked so hard!
O que é Blockchain?
Tags: web3, programming, blockchain
Published: 2022-05-26 21:01:00

_De uma forma simples para você aprender._

![datadriveninvestor](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3eeht5568j0rjs0xmeaa.png)
 
Imagine um cubo de vidro pequeno que cabe na sua mão e dentro dele há um papel escrito nos dois lados o seu nome completo. Independente do lado que você vire o cubo, você vai conseguir enxergar o seu nome completo. 

Essa transparência é uma das propriedades da **Blockchain**.

Com algum espaço de tempo, o seu vizinho resolve fazer o mesmo. Anotou o nome dele nos dois lados dentro do cubo de vidro, e consegue enxergar. O terceiro vizinho também resolve fazer o mesmo. Assim, sucessivamente e infinitamente. É assim que a Blockchain funciona! É uma cadeia de blocos ligadas umas as outras, onde você consegue ter total transparência das ações e assegurando de não haver imutabilidade. 

Isso mesmo! Blockchain não pode ser mutável. Depois que você escreveu no seu cubo, a informação que foi escrita, jamais poderá ser modificada.

Por fim, cada bloco é ligado um ao outro, conforme dito anteriormente, e o tempo de emissão de um novo bloco com as informações varia de acordo com a Blockchain. 

Exemplo disso, a Ethereum tem uma média de 10 à 20 segundos. Enquanto o Bitcoin têm 10 minutos para minerar o próximo bloco.

_That's it!_

_Espero que tenha facilitado a compreensão dessa tecnologia que está vindo com força total._
What's Your Preferred RPC Mechanism and Why?
Tags: webdev, discuss, cloud, api
Published: 2022-05-26 20:58:23

What it says on the tin. What kind of mechanism do you prefer for your web APIs? Where would you use it? Where wouldn't you?

Examples:

- gRPC
- JSON over HTTP (RESTful, usually)
- Binary over WebSockets
- Custom UDP (e.g. for real-time game networking?)
React Project
Tags: react, programming
Published: 2022-05-26 20:50:14

Facebook created React.js in 2011 for their own use. As you know, Facebook is one of the biggest Social Networking websites in the world today.

In 2012, Instagram also started using it, which is a subsidiary of Facebook.

In 2013, Facebook made React.js open-sourced. Initially, the developer community rejected it because it used Markup and JavaScript in a single file. But as more people experimented with it, they started embracing the component-centric approach for separating concerns.

When I first start studied react, I felt the concept are similar to what we had in javascript but somehow it's not the same. The same patter also happened when we later get into practice code challenge, with some example I can finish the coding and make it compiles. But I don't feel the happiness of making it because I don't fully understand why it works. Only after working on greglist, plantsy and some other mock challenge it became clear to me.

But I want to recommend because React is remarkably flexible. Once you have learned it, you can use it on a vast variety of platforms to build quality user interfaces. React is a library, NOT a framework. '
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kk7wy8pskjfngs7ibvy4.png)
Bug Bounty vs. Security Scanner
Tags: security, bug, startup, programming
Published: 2022-05-26 20:41:14

A lot of folks don't know the difference between a bug bounty program and automated security scans. Here is a cheat sheet to quickly learn the major differences. 

Synonyms

Security scanner is also known as a web application scanner or DAST. DAST stands for Dynamic Application Security Testing. 

DAST is the process of testing web, mobile, and API applications to find vulnerabilities and security bugs through simulated testing.

Ethical hacking is interchangeably used with these synonyms i.e.  Penetration Testing or Pen Testing or Ethical Hacking or Security Testing or Bug Bounty Programs.

Definition

DAST stands for Dynamic Application Security Testing. It is the process of testing web, mobile, and API applications to find vulnerabilities and security bugs through an automated approach.

Ethical hacking Is the process of finding security bugs through human intelligence. 
Most security testers might use and modify automated tools to find hard-to-find vulnerabilities.

Code Access

DAST: No code access is required. Most of the tools are language and technology agnostic
Ethical Hacking: No code access is required. Internal technology stack knowledge helps create tailored tests


Live Traffic Access:

No access to live traffic is required by both 

Support Technology Stacks:

DAST requires different tools for Web, Mobile, REST API, GraphQL, etc.

Ethical Hacking deploys all kinds of techniques including, manual web/mobile UI fuzzing, Burp tests for web/APIs, shell scripts, etc.

Common Vulnerabilities Found

With DAST we can usually find SQLi, XSS, Server Configuration, etc.

Ethical Hacking is commonly used to find Zero-day, logic flaws, unauthorized data access, account takeovers, access to PII/financial data, etc.
Pros

DAST can run continuously against the dev environment

Ethical Hacking find hard-to-find vulnerabilities
Cons

DAST has limited coverage and finds less-frequently found issues

Ethical Hacking is done less frequently, most companies perform penetration testing once every 3/6/12 months.

Cost

DAST needs Low-cost whereas Ethical Hacking is always high in cost.

Developer Friendly

Scanner findings are spread across production setup and code. Not all findings require developers to fix them. E.g. server configurations, SSL, etc, require the DevOps or the production support team to fix it.
The developers hate or don’t get a lot of the suggestions. Working with developers is a major pain point.

When it comes to Ethical Hacking, most findings require developers to fix the issues and are  code-related problems which are regular bugs. Developers get most of the issues and they will   happily add them to their bug list.


Popular Tools

Free API Scanner
https://apisec-inc.github.io/pentest/

Qualys Web app Scanner
https://www.qualys.com/apps/web-app-scanning/


Mobile App Scanner
https://www.ostorlab.co/

Bug Bounty Program
https://www.hackerone.com/

Web app testing
https://portswigger.net/burp/communitydownload
AWS EC2 Tag based folder access to S3
Published: 2022-05-26 20:39:14

Recently I have been developing a multi tenant system in where each user was assigned an EC2 that contained a full stack deployment of a web app. This EC2 also needed to have access to access to a folder in a S3 bucket where the tenant could upload anything they want **but only to their designated folder** in the bucket.

This posed quite a challenge to make this scaleable (i.e I want to make the policy once, and it should scale regardless of how many tenant I sign on) as I discovered many different account limitations with different approaches. 

One method of achieving this was to assign 1 IAM User per Tenant. I can then make a policy that is attached to each user saying that "**Tenant X** can only access **X Folder** in this bucket". Great solution, but we have our first hiccup. 

**AWS limits the amount of users to 5,000.** This means I can only onboards up to 5000 tenants before having to create another AWS account. Not ideal.
Binary
Published: 2022-05-26 20:01:47

How does binary do… everything?
Hello, I have very limited knowledge on computer science (made stuff on processing.is as a kid) and really have only taken a broader interest as I’ve started learning the object based music programming software Max MSP. Used Arduinos a little.

This is probably a dumb question but I was wondering if anyone could explain this or send me in the direction of some resources to read n learn more - how is it that binary is able to create everything in a computer? I understand the whole on/off principle on circuit boards and it makes sense how permutations of 1 and 0 can make more numbers, but how can a series of 1/0 on/off inputs eventually allow things like, if statements, or variables that can change - the sort of building blocks that allow code? How do you move beyond simply indexing numbers? There’s a mental gap for me. Does it have to do more with how computers are built mechanically?
JavaScript Array Methods: join()
Tags: javascript, programming, tutorial
Published: 2022-05-26 19:53:27

I was training on the CodeWars when I had a problem: write a function where your returns is a string of array.
Ex: ['hello', 'world'] to 'hello world'

You can use the method join() to do that for you.

The function looked like: 

_function arrayToString(words)
{
   return words.join(" ")
}_

It's so simple, alright?

The method join by default return a string separate with ',', something be like: 'hello, world', using the last example as example.

But you can separate too with spaces, just use join(" ")
The example will stay: 'hello world'.

*sorry for low level english, im studying *
Why you need a blog (as a software engineer)
Published: 2022-05-26 19:38:50

Landing your first job in tech is tough for everyone, even more so if you are a self-taught software engineer or a bootcamp graduate.

In this video I share why having a blog might help you find your first tech job quicker.

{% embed https://youtu.be/BktQLdvOq-4 %}

[Subscribe](https://www.youtube.com/channel/UCwkrS1KQCC9jlTriI6m9xuQ?sub_confirmation=1) to my channel if you don't want to miss upcoming videos about building a career in tech.
CodeAcademy Backend Project: E-Commerce
Tags: javascript, codeacademy, express, webdev
Published: 2022-05-26 19:24:17

Hi Im Johan Bell, Student Trainee. I am training on CodeAcademy by doing the FullStack Engineering Path and i am a new commer on dev.to network. 
Please, i have some questions a specific task: It has been asked to me to setup a local login. During the course we learnt by using PassportJs. I have to strucute my Code by using MCV pattern. 

Now, i dont which section of the code is going in the Controller, Model and the view to set the local login up. Does anyone has been working on it before or knows how to proceed ?

Thanks in Advance