Skip to content

Commit ed22430

Browse files
committed
feat: i18n translation en
1 parent e4b9346 commit ed22430

26 files changed

+483
-480
lines changed

docs/en/backend/api.md

+12-12
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,22 @@
1-
# Абстракция канала связи с бэкендом
1+
# Backend link abstraction
22

3-
## API сервис
3+
## API service
44

5-
Для осуществления вызовов на бэк удобно выделить код, связанный с транспортным уровнем (формирование и отправка запроса) в отдельный js модуль.
5+
To make calls to the backend, it is convenient to separate the code related to the transport layer (forming and sending a request) into a separate js module.
66

7-
Тогда в вашем компоненте доступ к вашему бэкенду будет выглядеть примерно так:
7+
Then in your component access to your backend will look like this:
88

9-
```js
9+
``js
1010
import { api } from "@/services/api";
1111

1212
// loading.value = true;
1313
const userData = await api.users.getUserData({ userId });
1414
// loading.value = false;
1515
```
1616
17-
Вся сложность связи с бэкендом спрятана в модуль `api`.
17+
All the complexity of backend communication is hidden in the `api` module.
1818
19-
Пример `api.js`:
19+
Example `api.js`:
2020
2121
```js
2222
import auth from "./auth";
@@ -42,11 +42,11 @@ const api = {
4242
},
4343
};
4444
45-
export { api };
45+
export { api }
4646
export default api;
4747
```
4848

49-
Пример `users.js`
49+
Example `users.js`
5050

5151
```js
5252
import http from "./http";
@@ -58,8 +58,8 @@ const users = {
5858
};
5959
```
6060

61-
`http.js` - обертка вокруг запросов на сервер через вашу любимую библиотеку.
61+
``http.js` is a wrapper around requests to the server via your favorite library.
6262

63-
Чем удобно абстрагирование кода связи с бэкендом от основного кода приложения в отдельный сервис?
63+
What is the convenience of abstracting the backend communication code from the main application code into a separate service?
6464

65-
Можно легко заменить `axios` на `fetch` или `XHR`, `REST` на `JSON-RPC` или `WebSockets`. Код в компонентах не меняется и остается простым и явным.
65+
You can easily replace `axios` with `fetch` or `XHR`, `REST` with `JSON-RPC` or `WebSockets`. The code in the components does not change and remains simple and explicit.

docs/en/backend/auth.md

+29-29
Original file line numberDiff line numberDiff line change
@@ -1,66 +1,66 @@
1-
# Аутентификация и авторизация
1+
# Authentication and authorization
22

3-
::: details Что такое аутентификация и авторизация
4-
Грубо говоря:
3+
::: details What is authentication and authorization
4+
Roughly speaking:
55

6-
Аутентификация - когда система удостоверяется, что в неё залогинился именно Вася Пупкин, например, проверив его логин и пароль
6+
Authentication is when the system verifies that it is Vasya Pupkin who logged in, for example, by checking his username and password
77

8-
Авторизация - когда система удостоверяется, что запрашивающий ресурс/действие пользователь имеет право доступа к нему. Например, старший менеджер имеет право удаления товара в админке, а простой менеджер - нет.
8+
Authorization - when the system verifies that the user requesting the resource/action has the right to access it. For example, a senior manager has the right to delete an item in the admin, but a simple manager does not.
99
:::
1010

11-
::: details Как сделать систему аутентификации на сайта
11+
:::: details How to make an authentication system on the site
1212

13-
Для SPA самый распространенный способ - на JWT токенах. Вариантов это сделать много, в зависимости от требований уровня безопасности (личный блог Васи Пупкина с комментариями гостей и онлайн магазин с депозитами и бонусами - две большие разницы).
13+
For SPA the most common way - on JWT tokens. There are many variants of this, depending on the requirements of the security level (Vasya Pupkin's personal blog with guest comments and online store with deposits and bonuses - two big differences).
1414

15-
JWT - это стандарт записи небольшого количества информации в строку (токен) и подписывания её (криптография). Делает это бэкенд. Таким образом только бэкенд может удостовериться, что токен выписан им, и в нем действительная информация.
15+
JWT is a standard for writing a small amount of information into a string (token) and signing it (cryptography). It is done by the backend. So only the backend can make sure that the token is written by it and has valid information in it.
1616

17-
Стандарта аутентификация на токенах как такового нет, есть лучшие практики.
17+
There is no standard for token authentication as such, there are best practices.
1818

19-
Варианты:
19+
Options:
2020

21-
1. Бэкенд генерит токен (access token - AT) и кладет в httpOnly cookie. Фронтэнд доступа к токену не имеет, браузер просто возвращает куку. Метод незаслужено редко используемый, но вполне надежный. С фронта снимаются все заморочки по манипуляции с АТ.
21+
1. backend generates token (access token - AT) and puts it in httpOnly cookie. The frontend does not have access to the token, the browser just returns the cookie. This method is undeservedly rarely used, but it is quite reliable. The frontend removes all the hassles of manipulating AT.
2222

23-
Сценарий:
23+
Scenario:
2424

25-
- Фронт логинится, получает данные пользователя с бэка и работает с ними. При получении при любом запросе 401 - направляет пользователя на форму логина, обнуляет данные пользователя.
26-
- Бэк при логине создает httpOnly cookie с токеном с определенным сроком жизни. На каждом запросе проверяет токен, определяет того, кому выписан этот токен и его права, и дальше решает разрешать ли доступ. Если срок жизни токена кончился - возвращает 401.
25+
- Front logs in, gets user data from the backend and works with it. When receiving any 401 request, it directs the user to the login form and resets the user data to zero.
26+
- Back at login creates httpOnly cookie with token with certain lifetime. At each request it checks the token, determines the person to whom this token is issued and his rights, and then decides whether to allow access. If the lifetime of the token has expired, it returns 401.
2727

28-
2. Бэкенд генерит токен (access token - AT) и передаёт фронту. Фронт сохраняет его и каждый раз отправляет его обратно. По сути то же самое, что и в первом случае, плюс лишние телодвижения и возможность потерять токен через XSS.
28+
2 The backend generates an access token (AT) and passes it to the front. The front saves it and sends it back each time. In essence the same as in the first case, plus unnecessary steps and the possibility of losing the token through XSS.
2929

30-
3. Используются два токена - короткоживущий access token (AT) и дольше живущий refresh token (RT) пересылаемый в httpOnly cookie. AT работает как во втором случае. Когда записанный в нем срок его жизни кончается, бэкенд проверяет RT, и если он валиден, обновляет AT. Кончается RT - пользователь направляется на перелогин.
30+
3. two tokens are used - short-lived access token (AT) and longer-lived refresh token (RT) sent in httpOnly cookie. AT works as in the second case. When its lifetime expires, the backend checks the RT and if it is valid, refreshes the AT. RT expires - the user is sent to re-login.
3131

32-
Подробнее по данной теме можно ознакомиться в, например, [этой статье](https://habr.com/ru/articles/710552/)
32+
More details on this topic can be found in, for example, [this article](https://habr.com/ru/articles/710552/).
3333

3434
:::
3535

36-
::: details Где хранить access token на фронте?
36+
:::: details Where to store access token on the frontend?
3737

38-
В 95% случаев в LocalStorage
38+
In 95% of cases in LocalStorage
3939

4040
:::
4141

42-
::: details Что такое oAuth и SSO?
42+
:::: details What is oAuth and SSO?
4343

44-
oAuth - Логин "через Google". Также когда, например, у пользователь есть возможность на твоем сайте сохранить что-то в Google Drive. Чтобы получить разрешение для твоего сайта работы с Google Drive аккаунтом пользователя, ты просишь его дать через Google разрешения твоему сайту лазить в его аккаунт. Итого у нас есть четыре части - Google (авторизационный центр), сторонний ресурс (Google Drive), твой сайт и пользователь
44+
oAuth - Login "via Google". Also when, for example, a user has the option on your site to save something to Google Drive. In order to get permission for your site to work with the user's Google Drive account, you ask the user to allow your site to access their account via Google. So we have four parts - Google (the authorization center), the third-party resource (Google Drive), your site, and the user
4545

46-
SSO - single sign-on - логин пользователя на портал некой компании один раз, и затем прозрачный доступ на разные его сервисы. Например, логин в GMail и доступ в сразу в Google Диск, Google Photo и так далее.
46+
SSO - single sign-on - a user logs in to a certain company's portal once, and then has transparent access to its different services. For example, login to GMail and access to Google Drive, Google Photo and so on.
4747

4848
:::
4949

50-
::: details Дает ли аутентификация через JWT безопасность?
50+
:::: details Does authentication via JWT give security?
5151

52-
Безопасность - очень комплексное понятие, аутентификация через JWT - всего лишь один из её элементов. Для критичных приложений можно снимать отпечаток системы пользователя (browser fingerprint) и заставлять пользователя перелогиниваться как только он изменился. То же самое с IP. Таким образом можно бороться с кражей АТ. Также ставить очень маленький срок жизни AT, если используется RT. Но основные меры безопасности связаны не с аутентификацией, а с постоянным мониторингом системы на подозрительные действия.
52+
Security is a very complex concept, and JWT authentication is just one of its elements. For critical applications, it is possible to capture the user's browser fingerprint and force the user to re-login as soon as they change. Same with IP. In this way you can fight AT theft. Also set very small AT lifetime if RT is used. But the main security measures are not related to authentication, but to constant monitoring of the system for suspicious actions.
5353

5454
:::
5555

56-
::: details Авторизация
56+
:::: details Authorization
5757

58-
Если нужно давать пользователям разный уровень доступа к ресурсам сайта, то обычно применяется или RBAC (Role-based access control) или PBA - Policy-Based Authorization (Permission-Based Authorization).
58+
If it is necessary to give users different levels of access to site resources, it is common to use either RBAC (Role-based access control) or PBA (Policy-Based Authorization).
5959

60-
В первом случае пользователи распределяются по ролям (админ, менеджер, юзер) и уровень доступа определяется ролью.
60+
In the first case, users are assigned to roles (admin, manager, user) and the level of access is determined by the role.
6161

62-
Во-втором можно более гранулировано задать разрешение каждому пользователю индивидуально на любое действие.
62+
In the second case, it is possible to set permissions for each user individually for any action in a more granular way.
6363

64-
Нужно понимать, что на фронте авторизация делается для удобства (пользователь не видит разделы сайта, которые ему запрещены), но за безопасность отвечает бэк - он должен проверять каждый раз, имеет ли пользователь право доступа к запрашиваемому ресурсу, даже если на фронте его как бы видно не должно быть. Сломать фронт - очень несложно.
64+
It should be understood that on the front authorization is done for convenience (the user does not see the sections of the site that are forbidden to him), but the back is responsible for security - he must check each time whether the user has the right to access the requested resource, even if on the front it should not be visible. It is not very difficult to break the front end.
6565

6666
:::

0 commit comments

Comments
 (0)