teleren/devto huggingface dataset:
Setting Up User Auth With React and Rails Minus The JWT Headache
Tags: react, rails, devise
Published: 2022-12-22 23:53:44

## Problem
Most of the tutorials that I've encountered on setting up User Auth for React and Rails with Devise involves the following components:

- Rails API
- Devise
- CORS setup for Rails
- Some sort of JWT library like Doorkeeper or devise-jwt
- Use of localStorage to store the JWT token.

The are multiple problems with the above setup. The most important of which is storage of the JWT token in localStorage. This is not a safe method as other JS would have access to localStorage and the JWT can be compromised.

The second problem with this method is how much work it takes to complete the setup.

## Solution
Turns out a secure HTTP Cookie is the most secure method of storing the user session data on the frontend. 

- Rails (none-API)
- Devise
- nginx

*Notes:* I will not go over the initial Rails or Devise setup in this document as it is very well documented through Rails and Devise documentation.

The key to this solution working is the using the same domain for the frontend and the backend.

### Repo Setup
React application and Rails application do not be in the same repo and React application does not be setup as part of the Rails application for this solution to work.

## Steps

- Setup Rails and Devise following steps from their respective documentation.
- Setup puma to run on a different port than React either by updating `config/puma.rb` to include 
```
port ENV.fetch("PORT") { 3001 }
``` 
or using the `-p` option: 
```
rails s -p 3001
```
In my case I have chosen port 3001
- Setup the React Application.
- Setup nginx:
We will use nginx as a proxy pass to redirect calls to `/` to the React frontend and the calls to `/api` to the Rails backend.

```
# /etc/nginx/sites-available/default
server {
	listen 80;
	listen [::]:80;

	server_name my.amazing.website.com;

	location / {
		 proxy_pass http://127.0.0.1:3000;
	}

	location /api {
		 proxy_pass http://127.0.0.1:3001;
	}
}
```
- Restart nginx to load the new configuration
`sudo service nginx reload`
- Place the users routes under the `/api` scope
```
  scope '/api' do
    devise_for :users
  end
```
- Enable rails to respond to json requests by adding the following to the ApplicationController 
```  
respond_to :json
```
- Allow Rails to accept post requests w/o providing an authenticity token by adding the following to the ApplicationController
```
skip_before_action :verify_authenticity_token
```
Building a MacOS Clone in TypeScript React 🍏
Tags: typescript, react, webdev, javascript
Published: 2022-12-22 23:46:10

> So, recently I did a thing...

To preface said "thing", I was just getting done with my final project as I'm heading towards the end of my degree and wanted to start applying for a development role.

**HOWEVER**, I am probably not the only one with the infamous imposter-syndrome, so I felt like I still lacked a lot of the muscle memory and familiarity with some concepts, most importantly with APIs, though. My best guess was that I should build a little project that would force me to work with APIs more so that I would get a bit more exposure to them.

So I did. I actually wanted to start building a "weather-app". 🤦‍♂️

**The** most overused project in web-development history. I know, I know. Which is exactly why I didn't feel good about it. Sure, I learned a thing here or there but it didn't look good, it didn't use any modern tech (like motion libraries or pre-processors) because it simply didn't need them. Which is fair, but it also didn't feel like it was a project worth showing of and it was far below the standards I had for myself.

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fo24t4bfg03gkbzwq4dp.PNG)

So I built a MacOS around it and integrated my weather app as one of the apps in the famous MacOS desktop dock. Now, I could say a lot about the project, about what I implemented and how I did so, about what I learned etc. but I think the project and my pretty rich readme.md file speak for themselves this time!

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zfciujk8yweqpilblw3c.PNG)

Feel free to check it out and feel even more free to leave any kind of constructive criticism either below or in an issue in it's repository. Cheers and happy holidays!

🔴 Live Link: https://gianlucajahn.github.io/macOS-react/
🔌 Repository: https://github.com/gianlucajahn/macOS-react
Es buena práctica utilizar formularios dentro de una modal?
Tags: ux, web, forms, modal
Published: 2022-12-22 23:45:44


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

Es posible utilizar formularios dentro de un modal, pero es importante tener en cuenta algunos aspectos para asegurar una buena experiencia de usuario.


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


Algunas de las ventajas de utilizar formularios dentro de un modal son:

1. Permiten mostrar información relevante sin necesidad de cambiar de página, lo que puede ser más rápido y sencillo para el usuario.

2. Ayudan a mantener el contexto y evitar distracciones, ya que el usuario sabe que se encuentra en el mismo lugar y sólo se centra en el formulario.


Sin embargo, es importante tener en cuenta algunos puntos para asegurar una buena experiencia de usuario:

3. Asegúrate de que el tamaño del modal sea adecuado para el formulario y que no sea demasiado grande o pequeño.

4. Utiliza títulos y etiquetas claras para indicar el propósito del formulario y facilitar la comprensión del usuario.

5. Proporciona instrucciones adecuadas y utiliza herramientas de validación para evitar errores y acelerar el proceso de rellenado del formulario.

6. Ofrece la opción de cerrar o cancelar el modal si el usuario no desea completar el formulario.

En general, utilizar formularios dentro de un modal puede ser una buena opción si se hace de manera adecuada y teniendo en cuenta la experiencia del usuario.

[☕ Invitarme un café](https://www.buymeacoffee.com/manuelmorales)
MovingLake - Real-time data connectors for hospitality and eCommerce
Tags: hospitality, analytics
Published: 2022-12-22 23:38:55

MovingLake provides state-of-the-art real-time data connectors for infrastructure, hospitality, and e-commerce. 

Power your data warehouse, databases, and data lakes, as well as your microservices using the same API connectors, and get consistent data across all your systems.

Make data-driven decisions faster with MovingLake!

[https://www.movinglake.com](https://www.movinglake.com)
Open Swoole 22.0.0 released
Tags: php, webdev, swoole
Published: 2022-12-22 22:45:54

10 years after beginning of Swoole, OpenSwoole 22.0.0 is released.

Open Swoole is a major fork of Swoole. His first pecl package was released in october 2021.

The good thing about it is all documentation is in english on their website [https://openswoole.com](https://openswoole.com)
Season 2 Finale: Holidays, 2022’s Favorite Moments, Season 3 Sneak Peek & more!
Tags: podcast, devops, management, programming
Published: 2022-12-22 22:42:55

Sit back, relax, grab your favorite beverage and listen as Dev Interrupted co-hosts Dan Lines & Conor Bronsdon recap the Season 2 of the podcast. 

In this special episode, our co-hosts describe their perfect holiday meal, share some of their favorite moments from the past year (personal and professional!) and give a sneak peek at what the audience can expect from Season 3 of the podcast.

From our family to yours, have a wonderful holiday season and we’ll see you on January 3rd for Season 3!

{% spotify spotify:episode:68jW6qjLEz8qsfQa0rywW4 %}

## Episode Highlights:
* (2:19) Holidays and family
* (8:03) Dev Interrupted Wrapped
* (13:45) Favorite guests and topics from Season 2
* (16:27) Dan's 3 lessons from this season
* (23:23) Season 3 sneak peek

***While you’re here, check out this video from our [YouTube channel](https://www.youtube.com/c/DevInterrupted?sub_confirmation=1), and be sure to like and [subscribe](https://www.youtube.com/c/DevInterrupted?sub_confirmation=1) when you do!*** 

{% youtube _BkyfXXY-oU %}

### Want to cut code-review time by up to 40%? Add estimated review time to pull requests automatically!
*gitStream is the free dev tool from LinearB that eliminates the No. 1 bottleneck in your team’s workflow: pull requests and code reviews. After reviewing the work of 2,000 dev teams, LinearB’s engineers and data scientists found that pickup times and code review were lasting 4 to 5 days longer than they should be.* 

*The good news is that they found these delays could be eliminated largely by adding estimated review time to pull requests!*

### Learn more about how gitStream is making coding better [HERE](https://linearb.io/blog/why-estimated-review-time-improves-pull-requests-and-reduces-cycle-time/?utm_source=Substack%2FMedium%2FDev.to&utm_medium=referral&utm_campaign=gitStream%20-%20Referral%20-%20Distribution%20Footers).

![Start using gitstream today!](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xg1l6hxt134px501bf7d.png)
Carbon-design-system for Svelte: dynamic import is your only solution !
Tags: svelte, webdev, tricksntips
Published: 2022-12-22 22:26:46

> **DISCLAIMER**: install sveltekit, carbon design with sveltekit+vite works out of the box !

I've opened issue on [IBM community](https://github.com/carbon-design-system/carbon-components-svelte/issues/1564) to find a solution rather than importing via `<svelte:head>`, although I could not even get any answer to that . After sometime of scratching my head and couple of tests on Webpack behaviour, I've managed to crack [carbon-design-system for Svelte](https://carbon-components-svelte.onrender.com/) once and for all . Repeating myself:

> **POSSIBLE REASON WHY WE NEED DYNAMIC IMPORT RATHER THAN STATIC ONE IS** : Svelte acts asynchronously subsequently static import at svelte compiler build stage has not YET registered Carbon-design, in order to upload the Carbon-design theme files (CSS) via Svelte to Dom stage, common sense, you must use dynamic import, onMount cycle just makes sure theming would load within first Svelte load

**<u>package.json</u>**

```javascript
// webpack.config.js
...
 resolve: {
    modules: [
      'node_modules'
    ],
}
...
```

---

**<u>App.svelte</u>**

```js
// App.svelte
        onMount(async ()=>{
            // e.g. import ./white.css theme:
            await import("carbon-components-svelte/css/white.css")
       })
```

Enjoy coding with Svelte `<3`
ReductStore Client SDK for Python v1.2.0: New Features and Example Use
Tags: news, python, database, reductstore
Published: 2022-12-22 22:14:52


Hello, everyone!
We are excited to announce the release of
the [Python client SDK v1.2.0](https://github.com/reductstore/reduct-py/releases/tag/v1.2.0)! This release includes
support for the
[ReductStore HTTP API v1.2](https://github.com/reductstore/reductstore/releases/tag/v1.2.0) and several other
improvements.

One of the new features in this release is the `Client.me()` method. This method allows you to get information about the
current token being used to authenticate with the ReductStore instance. It returns a `FullTokenInfo` object, which
contains
information about the token, including its name, creation time, and permissions.

To use the method, simply call it on a Client instance:

```python
from reduct import Client

client = Client('https://play.reduct.store', api_token='my-token')

# Get the current token info
token_info = await client.me()

# Print the token name and creation time
print(f"Token name: {token_info.name}")
print(f"Token created at: {token_info.created_at}")

# Print the token permissions
print(f"Full access: {token_info.permissions.full_access}")
print(f"Read access: {token_info.permissions.read}")
print(f"Write access: {token_info.permissions.write}")
```

In addition to the `Client.me` method, this release also includes improvements to the documentation and a migration to
using a
`pyproject.toml` file to manage dependencies.

To upgrade to the latest version of the reduct-py SDK, run the following command:

```
pip install -U reduct-py
```

if you have any questions or feedback, don't hesitate to reach out in [Discord](https://discord.gg/NQbPeGgzdR)
or by opening a discussion on [GitHub](https://github.com/reductstore/reductstore/discussions).
Bonjour ou bonsoir à tous! Hi !
Published: 2022-12-22 22:09:06

Nouvelle sur ce site et dans métier.je souhaiterais monter en compétences dans le développement web. Si vous avez des idées de e portfolio n hésitez pas à me les faire partager. 

New on this site and in profession. I would like to improve my skills in web development. If you have any ideas for an e-portfolio, don't hesitate to share them with me.
Fetch Statements
Tags: javascript, beginners, programming
Published: 2022-12-22 21:57:44

fetch('http://example.com/movies.json')
  .then((response) => response.json())
  .then((data) => console.log(data));

This looks to be something simple to use and and work with.
And it can be. What I have learned about using fetch is a winding rocky road. To start with, always check the URL(address), make sure it has the correct spelling and includes the endpoint that need or are using. Once that is working and you are getting a good response in the console, you need to start feeding it information related to your project. Here is an example of one that I wrote as a practice project: 

// 
fetch(url)  <-gets the information from the API that you are using->
   ~ .then((response) => response.json()) <-converts the information into a readable format.->

   ~ .then((movies) => { <-This starts the iteration loop that will allow the proper information that come from the API to display on the page.->
    ~    movies.map(renderMovie) <-In this example, this line grabbed the picture of the movie and displayed it on the HTML page.->
     ~   movies.map(displayInfo) <-This line grabbed the remaining details (Title, Year it was released, and a brief description of the movie itself.->
     }); 
//

It can be a confusing spot to get worked out of, just do not give up. We are all learning this together. 

-getGoodNerd
Sequential API keras tensorflow
Tags: tensorflow, python, programming, tutorial
Published: 2022-12-22 21:54:07

The Sequential API is a way to create a neural network model in Keras, a popular deep learning library. It allows you to build a model layer by layer, in a linear fashion, by specifying the input layer and the output layer, and then adding any number of hidden layers in between.

Here's an example of how you can use the Sequential API to create a simple fully-connected network with two hidden layers:

```
from keras.models import Sequential
from keras.layers import Dense

# Create a Sequential model
model = Sequential()

# Add a hidden layer with 64 units and ReLU activation
model.add(Dense(64, activation='relu', input_shape=(input_shape,)))

# Add another hidden layer with 64 units and ReLU activation
model.add(Dense(64, activation='relu'))

# Add the output layer with a single unit and sigmoid activation
model.add(Dense(1, activation='sigmoid'))

```


In this example, the input shape is specified in the first hidden layer. The model has two hidden layers with 64 units each and ReLU activation, and an output layer with a single unit and sigmoid activation.

You can then compile and fit the model using the compile and fit methods:

```
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

model.fit(x_train, y_train, epochs=10, batch_size=32)

```

This will train the model for 10 epochs on the training data x_train and y_train, using the Adam optimizer and binary cross-entropy loss. The model's accuracy will be tracked during training.
Writing More Effective Front-End Tests with Jest
Tags: webdev, testing, jest, frontend
Published: 2022-12-22 21:36:36

Front-end testing can be challenging as it often involves testing complex user interfaces and interactions. In this tutorial, we'll go over some tips for writing more effective front-end tests with Jest.

## Test the component, not the implementation

One of the key principles of front-end testing is to test the component, not the implementation. This means that you should focus on testing the output and behaviour of the component, rather that the specific implementation details.

For example, consider the following component:
```jsx
function MyButton(props) {
return <button onClick={props.oncClick}>{props.children}</button>
```
To test this component effectively, you should focus on testing the output (e.g. the rendered HTML) and the behaviour (e.g. the onClick event) rather than the specific implementation details (e.g. the fact that it uses a button element).

## Use the right test utilities

Jest provides a variety of test utilities that can make it easier to write effective front-end tests.

For example, the `@testing-library/react` library provides utility functions for rendering and interacting with React components in a test environment.

The `@testing-library/jest-dom` library provides additional utility functions for making assertions about the DOM, such as `expect(element).toHaveTextContent(text)` and `expect(element).toBeDisabled()`.

Using the right test utilities can make it much easier to write tests that are both effective and easy to maintain.

## Test asynchronous behaviour

Many front-end components have asynchronous behaviour, such as making network requests or updating the DOM after a delay. Testing this behaviour can be challenging, but Jest provides a variety of tools for handling asynchronous code in tests.

For example, you can use the `async` and `await` keywords to write asynchronous tests:
```jsx
test('async test', async () => {
const result = await asyncFunc();
expect(result).toEqual('hello');
});
```
You can also use the `done` callback to write asynchronous tests that don't use `async` and `await`:
```jsx
test('async test', (done) => {
  asyncFunc().then((result) => {
    expect(result).toEqual('hello');
    done();
  });
});
```
Testing asynchronous behaviour is essential for ensuring that your front-end components behave correctly in a real-world environment.

## Write testable components

Finally, it's important to design your front-end components in a way that makes them easy to test. This might involve extracting logic into separate functions, using props for input and state for output, and avoiding side effects where possible.

By writing testable components, you'll be able to write more effective tests that are easier to maintain and less prone to breaking when the implementation changes.

Credits:
<a href="https://www.freepik.com/free-vector/search-engine-marketing-business-copywriting-service-content-management_12085329.htm#query=testing&position=4&from_view=search&track=sph">Image by vectorjuice</a> on Freepik
Using the Rsync Command for Copying and Synchronizing Files and Directories
Tags: linux, rsync, commandline, filetransfer
Published: 2022-12-22 21:27:01

Rsync is a powerful Linux/Unix command that allows you to copy and synchronize files and directories between local and remote systems. It is particularly useful for synchronizing large numbers of files, as it is efficient and only transfers the differences between the source and destination files.

Here's a brief overview of how to use the Rsync command:

## Copying files and directories locally

To copy a file or directory from one location to another on the same system, you can use the following syntax:

`rsync <source> <destination>`

For example, to copy a file named file.txt from the current directory to the /tmp directory, you could use the following command:

`rsync file.txt /tmp`

To copy a directory and its contents, you can add the -r flag to the command:

`rsync -r <source> <destination>`

For example, to copy the /var/www/html directory and its contents to the /tmp directory, you could use the following command:

`rsync -r /var/www/html /tmp`

## Copying files and directories remotely

To copy a file or directory from a remote system to a local system, you can use the following syntax:

`rsync <user>@<remote_host>:<source> <destination>`

For example, to copy a file named file.txt from the /tmp directory on a remote system with hostname example.com to the current directory on your local system, you could use the following command:

`rsync user@example.com:/tmp/file.txt .`

To copy a directory and its contents, you can add the -r flag to the command as before:

`rsync -r <user>@<remote_host>:<source> <destination>`

For example, to copy the /var/www/html directory and its contents from a remote system with hostname example.com to the /tmp directory on your local system, you could use the following command:

`rsync -r user@example.com:/var/www/html /tmp`

## Synchronizing files and directories

To synchronize files and directories between two systems, you can use the -a flag, which stands for "archive" and preserves the file attributes and permissions. You can also use the -u flag, which stands for "update" and only transfers files that are newer on the source system:

`rsync -au <user>@<remote_host>:<source> <destination>`

For example, to synchronize the /var/www/html directory and its contents from a remote system with hostname example.com to the /tmp directory on your local system, making sure to only transfer newer files and preserve file attributes and permissions, you could use the following command:

`rsync -au user@example.com:/var/www/html /tmp`

Whether you're looking to simply copy files from one location to another, or synchronize entire directories between systems, Rsync can be a valuable tool to have in your toolkit. So give it a try and see how it can streamline your file management processes.

Credits:
<a href="https://www.freepik.com/free-vector/real-time-sync-concept-illustration_5842193.htm#query=synchronize&position=12&from_view=search&track=sph">Image by storyset</a> on Freepik