delete ald api on golang, moove file on yalarba project into one
directories
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
# Getting Started with Create React App
|
||||
|
||||
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
|
||||
|
||||
## Available Scripts
|
||||
|
||||
In the project directory, you can run:
|
||||
|
||||
### `npm start`
|
||||
|
||||
Runs the app in the development mode.\
|
||||
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
|
||||
|
||||
The page will reload when you make changes.\
|
||||
You may also see any lint errors in the console.
|
||||
|
||||
### `npm test`
|
||||
|
||||
Launches the test runner in the interactive watch mode.\
|
||||
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
|
||||
|
||||
### `npm run build`
|
||||
|
||||
Builds the app for production to the `build` folder.\
|
||||
It correctly bundles React in production mode and optimizes the build for the best performance.
|
||||
|
||||
The build is minified and the filenames include the hashes.\
|
||||
Your app is ready to be deployed!
|
||||
|
||||
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
|
||||
|
||||
### `npm run eject`
|
||||
|
||||
**Note: this is a one-way operation. Once you `eject`, you can't go back!**
|
||||
|
||||
If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
|
||||
|
||||
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
|
||||
|
||||
You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
|
||||
|
||||
## Learn More
|
||||
|
||||
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
|
||||
|
||||
To learn React, check out the [React documentation](https://reactjs.org/).
|
||||
|
||||
### Code Splitting
|
||||
|
||||
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
|
||||
|
||||
### Analyzing the Bundle Size
|
||||
|
||||
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
|
||||
|
||||
### Making a Progressive Web App
|
||||
|
||||
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
|
||||
|
||||
### Advanced Configuration
|
||||
|
||||
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
|
||||
|
||||
### Deployment
|
||||
|
||||
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
|
||||
|
||||
### `npm run build` fails to minify
|
||||
|
||||
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"files": {
|
||||
"main.js": "/static/js/main.9a8f7abd.js",
|
||||
"index.html": "/index.html",
|
||||
"main.9a8f7abd.js.map": "/static/js/main.9a8f7abd.js.map"
|
||||
},
|
||||
"entrypoints": [
|
||||
"static/js/main.9a8f7abd.js"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
<meta
|
||||
name="description"
|
||||
content="Web site created using create-react-app"
|
||||
/>
|
||||
<link rel="apple-touch-icon" href="/logo192.png" />
|
||||
<link rel="manifest" href="/manifest.json" />
|
||||
<title>React App</title>
|
||||
<script defer="defer" src="/static/js/main.9a8f7abd.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
<div id="root"></div>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* @license React
|
||||
* react-dom-client.production.js
|
||||
*
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @license React
|
||||
* react-dom.production.js
|
||||
*
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @license React
|
||||
* react-jsx-runtime.production.js
|
||||
*
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @license React
|
||||
* react.production.js
|
||||
*
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @license React
|
||||
* scheduler.production.js
|
||||
*
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
/**
|
||||
* react-router v7.7.0
|
||||
*
|
||||
* Copyright (c) Remix Software Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE.md file in the root directory of this source tree.
|
||||
*
|
||||
* @license MIT
|
||||
*/
|
||||
File diff suppressed because one or more lines are too long
+17602
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "easy-site",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@testing-library/dom": "^10.4.0",
|
||||
"@testing-library/jest-dom": "^6.6.3",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@testing-library/user-event": "^13.5.0",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0",
|
||||
"react-router-dom": "^7.7.0",
|
||||
"react-scripts": "5.0.1",
|
||||
"web-vitals": "^2.1.4"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "react-scripts start",
|
||||
"build": "react-scripts build",
|
||||
"test": "react-scripts test",
|
||||
"eject": "react-scripts eject"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": [
|
||||
"react-app",
|
||||
"react-app/jest"
|
||||
]
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
module.exports = {
|
||||
plugins: {
|
||||
tailwindcss: {}, // подключаем TailwindCSS
|
||||
autoprefixer: {} // подключаем автопрефиксер
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>EasySite102 – Лёгкий вход в цифровое присутствие для туризма</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: 'Arial', sans-serif;
|
||||
line-height: 1.6;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background-color: #f5f9ff;
|
||||
color: #333;
|
||||
}
|
||||
.container {
|
||||
max-width: 800px;
|
||||
margin: 50px auto;
|
||||
padding: 30px;
|
||||
background: white;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
|
||||
text-align: center;
|
||||
}
|
||||
h1 {
|
||||
color: #2a5ca7;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
p {
|
||||
margin-bottom: 25px;
|
||||
font-size: 18px;
|
||||
}
|
||||
.logo {
|
||||
font-size: 28px;
|
||||
font-weight: bold;
|
||||
color: #2a5ca7;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.cta {
|
||||
background: #2a5ca7;
|
||||
color: white;
|
||||
padding: 12px 30px;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
font-size: 16px;
|
||||
cursor: pointer;
|
||||
transition: background 0.3s;
|
||||
text-decoration: none;
|
||||
display: inline-block;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.cta:hover {
|
||||
background: #1e4a8f;
|
||||
}
|
||||
.features {
|
||||
display: flex;
|
||||
justify-content: space-around;
|
||||
flex-wrap: wrap;
|
||||
margin: 40px 0;
|
||||
}
|
||||
.feature {
|
||||
width: 30%;
|
||||
min-width: 200px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.icon {
|
||||
font-size: 40px;
|
||||
color: #2a5ca7;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
footer {
|
||||
margin-top: 40px;
|
||||
font-size: 14px;
|
||||
color: #777;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="logo">EasySite102</div>
|
||||
<h1>Ваш лёгкий старт в цифровом мире туризма</h1>
|
||||
<p>Помогаем средним пользователям интернета создать цифровое присутствие и внести вклад в развитие туристической отрасли без сложных технологий.</p>
|
||||
|
||||
<div class="features">
|
||||
<div class="feature">
|
||||
<div class="icon">🚀</div>
|
||||
<h3>Простота</h3>
|
||||
<p>Интуитивно понятные инструменты без технических сложностей</p>
|
||||
</div>
|
||||
<div class="feature">
|
||||
<div class="icon">🌍</div>
|
||||
<h3>Туризм</h3>
|
||||
<p>Специальные решения для продвижения туристических услуг</p>
|
||||
</div>
|
||||
<div class="feature">
|
||||
<div class="icon">📈</div>
|
||||
<h3>Результат</h3>
|
||||
<p>Быстрый выход на цифровые площадки и привлечение клиентов</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p>Сайт находится в разработке. Оставьте контакты, и мы сообщим о запуске!</p>
|
||||
<form action="#" method="POST">
|
||||
<input type="email" name="email" placeholder="Ваш email" required style="padding: 10px; width: 300px; max-width: 100%; border: 1px solid #ddd; border-radius: 5px; margin-right: 10px;">
|
||||
<button type="submit" class="cta">Узнать первым</button>
|
||||
</form>
|
||||
|
||||
<footer>
|
||||
© 2023 EasySite102. Все права защищены.<br>
|
||||
Контакты: info@easysite102.ru
|
||||
</footer>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,43 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
<meta
|
||||
name="description"
|
||||
content="Web site created using create-react-app"
|
||||
/>
|
||||
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
|
||||
<!--
|
||||
manifest.json provides metadata used when your web app is installed on a
|
||||
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
|
||||
-->
|
||||
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
|
||||
<!--
|
||||
Notice the use of %PUBLIC_URL% in the tags above.
|
||||
It will be replaced with the URL of the `public` folder during the build.
|
||||
Only files inside the `public` folder can be referenced from the HTML.
|
||||
|
||||
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
|
||||
work correctly both with client-side routing and a non-root public URL.
|
||||
Learn how to configure a non-root public URL by running `npm run build`.
|
||||
-->
|
||||
<title>React App</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
<div id="root"></div>
|
||||
<!--
|
||||
This HTML file is a template.
|
||||
If you open it directly in the browser, you will see an empty page.
|
||||
|
||||
You can add webfonts, meta tags, or analytics to this file.
|
||||
The build step will place the bundled scripts into the <body> tag.
|
||||
|
||||
To begin the development, run `npm start` or `yarn start`.
|
||||
To create a production bundle, use `npm run build` or `yarn build`.
|
||||
-->
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,38 @@
|
||||
.App {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.App-logo {
|
||||
height: 40vmin;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.App-logo {
|
||||
animation: App-logo-spin infinite 20s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.App-header {
|
||||
background-color: #282c34;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: calc(10px + 2vmin);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.App-link {
|
||||
color: #61dafb;
|
||||
}
|
||||
|
||||
@keyframes App-logo-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
|
||||
import Home from './pages/Home'; // главная страница
|
||||
import Login from './pages/Login'; // вход
|
||||
import Register from './pages/Register'; // регистрация
|
||||
import Dashboard from './pages/Dashboard'; // личный кабинет
|
||||
import AddObject from './pages/AddObject'; // добавить объект
|
||||
import EditObject from './pages/EditObject'; // редактировать объект
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<Router>
|
||||
<Routes>
|
||||
<Route path="/" element={<Home />} />
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/register" element={<Register />} />
|
||||
<Route path="/dashboard" element={<Dashboard />} />
|
||||
<Route path="/add-object" element={<AddObject />} />
|
||||
<Route path="/edit-object/:id" element={<EditObject />} />
|
||||
</Routes>
|
||||
</Router>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
@@ -0,0 +1,8 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import App from './App';
|
||||
|
||||
test('renders learn react link', () => {
|
||||
render(<App />);
|
||||
const linkElement = screen.getByText(/learn react/i);
|
||||
expect(linkElement).toBeInTheDocument();
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
// src/contexts/AuthContext.js
|
||||
import React, { useState, createContext, useEffect } from 'react';
|
||||
import axios from 'axios';
|
||||
|
||||
const AuthContext = createContext();
|
||||
|
||||
export const AuthProvider = ({ children }) => {
|
||||
const [currentUser, setCurrentUser] = useState(null);
|
||||
|
||||
const login = async (email, password) => {
|
||||
try {
|
||||
const response = await axios.post('/api/login', { email, password });
|
||||
if (response.data.token) {
|
||||
localStorage.setItem('token', response.data.token); // сохраняем токен в Local Storage
|
||||
setCurrentUser(response.data.user);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err.response ? err.response.data : err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const register = async (name, email, password) => {
|
||||
try {
|
||||
const response = await axios.post('/api/register', { name, email, password });
|
||||
if (response.data.token) {
|
||||
localStorage.setItem('token', response.data.token);
|
||||
setCurrentUser(response.data.user);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err.response ? err.response.data : err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
localStorage.removeItem('token');
|
||||
setCurrentUser(null);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const token = localStorage.getItem('token');
|
||||
if (token) {
|
||||
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ currentUser, login, register, logout }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export default AuthContext;
|
||||
@@ -0,0 +1,7 @@
|
||||
// src/contexts/useAuth.js
|
||||
import { useContext } from 'react';
|
||||
import AuthContext from './AuthContext';
|
||||
|
||||
export default function useAuth() {
|
||||
return useContext(AuthContext);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
|
||||
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
|
||||
sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
|
||||
monospace;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// src/index.js
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import { AuthProvider } from './contexts/AuthContext';
|
||||
import App from './App';
|
||||
|
||||
const root = ReactDOM.createRoot(document.getElementById('root'));
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<AuthProvider>
|
||||
<App />
|
||||
</AuthProvider>
|
||||
</React.StrictMode>
|
||||
);
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>
|
||||
|
After Width: | Height: | Size: 2.6 KiB |
@@ -0,0 +1,35 @@
|
||||
// src/pages/AddObject.js
|
||||
import React, { useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import useAuth from '../contexts/useAuth';
|
||||
import axios from 'axios';
|
||||
|
||||
const AddObject = () => {
|
||||
const auth = useAuth();
|
||||
const [title, setTitle] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
|
||||
const handleSubmit = async e => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
await axios.post('/api/add-object', { title, description }); // сюда ваш endpoint
|
||||
alert("Объект успешно добавлен!");
|
||||
} catch (err) {
|
||||
console.error(err.response ? err.response.data : err.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="container">
|
||||
<h2>Добавить объект</h2>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<input type="text" placeholder="Название" required onChange={(e) => setTitle(e.target.value)} /><br/><br/>
|
||||
<textarea rows="4" cols="50" placeholder="Описание" required onChange={(e) => setDescription(e.target.value)} /><br/><br/>
|
||||
<button type="submit">Добавить</button><br/><br/>
|
||||
<Link to="/dashboard">Вернуться в личный кабинет</Link>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AddObject;
|
||||
@@ -0,0 +1,58 @@
|
||||
// src/pages/Dashboard.js
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import useAuth from '../contexts/useAuth';
|
||||
import axios from 'axios';
|
||||
|
||||
const Dashboard = () => {
|
||||
const auth = useAuth();
|
||||
const [objects, setObjects] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchObjects = async () => {
|
||||
try {
|
||||
const response = await axios.get('/api/user/objects'); // заменить на нужный endpoint
|
||||
setObjects(response.data.objects);
|
||||
} catch (err) {
|
||||
console.error(err.response ? err.response.data : err.message);
|
||||
}
|
||||
};
|
||||
|
||||
fetchObjects();
|
||||
}, []);
|
||||
|
||||
// Функция подтверждения удаления объекта
|
||||
const confirmDelete = objId => {
|
||||
if (window.confirm('Вы действительно хотите удалить этот объект?')) {
|
||||
deleteObject(objId);
|
||||
}
|
||||
};
|
||||
|
||||
// Функция удаления объекта
|
||||
const deleteObject = async objId => {
|
||||
try {
|
||||
await axios.delete(`/api/delete-object/${objId}`); // заменить на правильный endpoint
|
||||
setObjects(prevObjects => prevObjects.filter(obj => obj.id !== objId));
|
||||
alert('Объект успешно удалён!');
|
||||
} catch (err) {
|
||||
console.error(err.response ? err.response.data : err.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="container">
|
||||
<h2>Ваш личный кабинет</h2>
|
||||
<ul>
|
||||
{objects.map(obj => (
|
||||
<li key={obj.id}>
|
||||
Название: {obj.title}, Описание: {obj.description}<br/>
|
||||
<Link to={`/edit-object/${obj.id}`}>Редактировать</Link> <a href="#" onClick={() => confirmDelete(obj.id)}>Удалить</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<Link to="/add-object">Добавить объект</Link>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Dashboard;
|
||||
@@ -0,0 +1,48 @@
|
||||
// src/pages/EditObject.js
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { useParams, Link } from 'react-router-dom';
|
||||
import useAuth from '../contexts/useAuth';
|
||||
import axios from 'axios';
|
||||
|
||||
const EditObject = () => {
|
||||
const auth = useAuth();
|
||||
const { id } = useParams(); // получаем ID объекта из маршрута
|
||||
const [object, setObject] = useState({});
|
||||
|
||||
useEffect(() => {
|
||||
const fetchObject = async () => {
|
||||
try {
|
||||
const response = await axios.get(`/api/get-object/${id}`);
|
||||
setObject(response.data.object);
|
||||
} catch (err) {
|
||||
console.error(err.response ? err.response.data : err.message);
|
||||
}
|
||||
};
|
||||
|
||||
fetchObject();
|
||||
}, [id]);
|
||||
|
||||
const handleSubmit = async e => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
await axios.put(`/api/edit-object/${id}`, object); // тут ваш endpoint
|
||||
alert("Объект успешно обновлён!");
|
||||
} catch (err) {
|
||||
console.error(err.response ? err.response.data : err.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="container">
|
||||
<h2>Редактировать объект №{id}</h2>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<input type="text" placeholder="Название" value={object.title || ""} onChange={(e) => setObject({...object, title: e.target.value})} /><br/><br/>
|
||||
<textarea rows="4" cols="50" placeholder="Описание" value={object.description || ""} onChange={(e) => setObject({...object, description: e.target.value})} /><br/><br/>
|
||||
<button type="submit">Обновить</button><br/><br/>
|
||||
<Link to="/dashboard">Вернуться в личный кабинет</Link>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default EditObject;
|
||||
@@ -0,0 +1,13 @@
|
||||
// src/pages/Home.js
|
||||
import React from 'react';
|
||||
|
||||
const Home = () => {
|
||||
return (
|
||||
<div className="container">
|
||||
<h1>Добро пожаловать!</h1>
|
||||
<p>Это ваше стартовая страница.</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Home;
|
||||
@@ -0,0 +1,28 @@
|
||||
// src/pages/Login.js
|
||||
import React, { useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import useAuth from '../contexts/useAuth';
|
||||
|
||||
const Login = () => {
|
||||
const auth = useAuth();
|
||||
const [formData, setFormData] = useState({ email: '', password: '' });
|
||||
|
||||
const handleSubmit = async e => {
|
||||
e.preventDefault();
|
||||
await auth.login(formData.email, formData.password);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="container">
|
||||
<h2>Вход</h2>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<input type="email" placeholder="Email" required onChange={(e) => setFormData({...formData, email: e.target.value})} />
|
||||
<input type="password" placeholder="Пароль" required onChange={(e) => setFormData({...formData, password: e.target.value})} />
|
||||
<button type="submit">Войти</button>
|
||||
<p>Нет аккаунта? <Link to="/register">Зарегистрируйтесь</Link></p>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Login;
|
||||
@@ -0,0 +1,29 @@
|
||||
// src/pages/Register.js
|
||||
import React, { useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import useAuth from '../contexts/useAuth';
|
||||
|
||||
const Register = () => {
|
||||
const auth = useAuth();
|
||||
const [formData, setFormData] = useState({ name: '', email: '', password: '' });
|
||||
|
||||
const handleSubmit = async e => {
|
||||
e.preventDefault();
|
||||
await auth.register(formData.name, formData.email, formData.password);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="container">
|
||||
<h2>Регистрация</h2>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<input type="text" placeholder="Имя" required onChange={(e) => setFormData({...formData, name: e.target.value})} />
|
||||
<input type="email" placeholder="Email" required onChange={(e) => setFormData({...formData, email: e.target.value})} />
|
||||
<input type="password" placeholder="Пароль" required onChange={(e) => setFormData({...formData, password: e.target.value})} />
|
||||
<button type="submit">Зарегистрироваться</button>
|
||||
<p>Уже зарегистрированы? <Link to="/login">Войти</Link></p>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Register;
|
||||
@@ -0,0 +1,13 @@
|
||||
const reportWebVitals = onPerfEntry => {
|
||||
if (onPerfEntry && onPerfEntry instanceof Function) {
|
||||
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
|
||||
getCLS(onPerfEntry);
|
||||
getFID(onPerfEntry);
|
||||
getFCP(onPerfEntry);
|
||||
getLCP(onPerfEntry);
|
||||
getTTFB(onPerfEntry);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export default reportWebVitals;
|
||||
@@ -0,0 +1,5 @@
|
||||
// jest-dom adds custom jest matchers for asserting on DOM nodes.
|
||||
// allows you to do things like:
|
||||
// expect(element).toHaveTextContent(/react/i)
|
||||
// learn more: https://github.com/testing-library/jest-dom
|
||||
import '@testing-library/jest-dom';
|
||||
@@ -0,0 +1,7 @@
|
||||
module.exports = {
|
||||
content: ['./src/**/*.{html,jsx,tsx}',],
|
||||
theme: {
|
||||
extend: {},
|
||||
},
|
||||
plugins: [],
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
# DB environment variabels
|
||||
DB_HOST=localhost
|
||||
DB_PORT=5432
|
||||
DB_USER=postgres
|
||||
DB_PASSWORD=postgres
|
||||
DB_NAME=mydb
|
||||
APP_PORT=8080
|
||||
@@ -0,0 +1,33 @@
|
||||
# Билд стадия
|
||||
FROM golang:1.25.1-alpine AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Копируем зависимости
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
# Копируем исходный код
|
||||
COPY . .
|
||||
|
||||
# Собираем приложение
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main ./cmd/api
|
||||
|
||||
# Финальная стадия
|
||||
FROM alpine:latest
|
||||
|
||||
RUN apk --no-cache add ca-certificates
|
||||
|
||||
WORKDIR /root/
|
||||
|
||||
# Копируем бинарник из builder стадии
|
||||
COPY --from=builder /app/main .
|
||||
|
||||
# Копируем миграции
|
||||
COPY --from=builder /app/migrations ./migrations
|
||||
|
||||
# Экспозим порт
|
||||
EXPOSE 8080
|
||||
|
||||
# Запускаем приложение
|
||||
CMD ["./main"]
|
||||
@@ -0,0 +1,27 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"serv_golang_rest_api/internal/config"
|
||||
"serv_golang_rest_api/internal/server"
|
||||
"serv_golang_rest_api/pkg/database"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Загрузка конфигурации
|
||||
cfg := config.Load()
|
||||
|
||||
// Подключение к БД
|
||||
db, err := database.NewPostgresConnection(cfg)
|
||||
if err != nil {
|
||||
log.Fatal("Failed to connect to database:", err)
|
||||
}
|
||||
|
||||
// Создание и запуск сервера
|
||||
srv := server.New(db)
|
||||
|
||||
log.Printf("Server starting on port %s", cfg.AppPort)
|
||||
if err := srv.Run(cfg.AppPort); err != nil {
|
||||
log.Fatal("Failed to start server:", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
services:
|
||||
api:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
ports:
|
||||
- "8888:8080"
|
||||
container_name: serv_golang_rest_api
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
# Database connection settings
|
||||
DB_HOST: db
|
||||
DB_PORT: 5432
|
||||
DB_USER: postgres
|
||||
DB_PASSWORD: postgres
|
||||
DB_NAME: mydb
|
||||
APP_PORT: 8080
|
||||
networks:
|
||||
- app-network
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/health"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
|
||||
db:
|
||||
image: postgres:15-alpine
|
||||
ports:
|
||||
- "5432:5432"
|
||||
environment:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: postgres
|
||||
POSTGRES_DB: mydb
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
- ./migrations:/docker-entrypoint-initdb.d
|
||||
networks:
|
||||
- app-network
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U postgres"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
|
||||
networks:
|
||||
app-network:
|
||||
driver: bridge
|
||||
@@ -0,0 +1,26 @@
|
||||
module serv_golang_rest_api
|
||||
|
||||
go 1.25.1
|
||||
|
||||
require (
|
||||
github.com/golang-jwt/jwt/v4 v4.5.2
|
||||
golang.org/x/oauth2 v0.31.0
|
||||
gorm.io/driver/postgres v1.6.0
|
||||
gorm.io/gorm v1.31.0
|
||||
)
|
||||
|
||||
require cloud.google.com/go/compute/metadata v0.3.0 // indirect
|
||||
|
||||
require (
|
||||
github.com/go-chi/chi/v5 v5.2.3
|
||||
github.com/go-chi/cors v1.2.2
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/pgx/v5 v5.6.0 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
golang.org/x/crypto v0.42.0
|
||||
golang.org/x/sync v0.17.0 // indirect
|
||||
golang.org/x/text v0.29.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,46 @@
|
||||
cloud.google.com/go/compute/metadata v0.3.0 h1:Tz+eQXMEqDIKRsmY3cHTL6FVaynIjX2QxYC4trgAKZc=
|
||||
cloud.google.com/go/compute/metadata v0.3.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/go-chi/chi/v5 v5.2.3 h1:WQIt9uxdsAbgIYgid+BpYc+liqQZGMHRaUwp0JUcvdE=
|
||||
github.com/go-chi/chi/v5 v5.2.3/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops=
|
||||
github.com/go-chi/cors v1.2.2 h1:Jmey33TE+b+rB7fT8MUy1u0I4L+NARQlK6LhzKPSyQE=
|
||||
github.com/go-chi/cors v1.2.2/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=
|
||||
github.com/golang-jwt/jwt/v4 v4.5.2 h1:YtQM7lnr8iZ+j5q71MGKkNw9Mn7AjHM68uc9g5fXeUI=
|
||||
github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.6.0 h1:SWJzexBzPL5jb0GEsrPMLIsi/3jOo7RHlzTjcAeDrPY=
|
||||
github.com/jackc/pgx/v5 v5.6.0/go.mod h1:DNZ/vlrUnhWCoFGxHAG8U2ljioxukquj7utPDgtQdTw=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI=
|
||||
golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8=
|
||||
golang.org/x/oauth2 v0.31.0 h1:8Fq0yVZLh4j4YA47vHKFTa9Ew5XIrCP8LC6UeNZnLxo=
|
||||
golang.org/x/oauth2 v0.31.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
|
||||
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
|
||||
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
|
||||
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4=
|
||||
gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo=
|
||||
gorm.io/gorm v1.31.0 h1:0VlycGreVhK7RF/Bwt51Fk8v0xLiiiFdbGDPIZQ7mJY=
|
||||
gorm.io/gorm v1.31.0/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
|
||||
@@ -0,0 +1,30 @@
|
||||
package config
|
||||
|
||||
import "os"
|
||||
|
||||
type Config struct {
|
||||
DBHost string
|
||||
DBPort string
|
||||
DBUser string
|
||||
DBPassword string
|
||||
DBName string
|
||||
AppPort string
|
||||
}
|
||||
|
||||
func Load() *Config {
|
||||
return &Config{
|
||||
DBHost: getEnv("DB_HOST", "localhost"),
|
||||
DBPort: getEnv("DB_PORT", "5432"),
|
||||
DBUser: getEnv("DB_USER", "postgres"),
|
||||
DBPassword: getEnv("DB_PASSWORD", "postgres"),
|
||||
DBName: getEnv("DB_NAME", "mydb"),
|
||||
AppPort: getEnv("APP_PORT", "8080"),
|
||||
}
|
||||
}
|
||||
|
||||
func getEnv(key, defaultValue string) string {
|
||||
if value := os.Getenv(key); value != "" {
|
||||
return value
|
||||
}
|
||||
return defaultValue
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// config/oauth.go
|
||||
package config
|
||||
|
||||
import (
|
||||
"golang.org/x/oauth2"
|
||||
"golang.org/x/oauth2/google"
|
||||
"golang.org/x/oauth2/yandex"
|
||||
"golang.org/x/oauth2/vk"
|
||||
)
|
||||
|
||||
|
||||
var (
|
||||
GoogleOAuthConfig = &oauth2.Config{
|
||||
ClientID: "your-google-client-id",
|
||||
ClientSecret: "your-google-client-secret",
|
||||
RedirectURL: "http://localhost:8080/auth/google/callback",
|
||||
Scopes: []string{"https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"},
|
||||
Endpoint: google.Endpoint,
|
||||
}
|
||||
|
||||
YandexOAuthConfig = &oauth2.Config{
|
||||
ClientID: "your-yandex-client-id",
|
||||
ClientSecret: "your-yandex-client-secret",
|
||||
RedirectURL: "http://localhost:8080/auth/yandex/callback",
|
||||
Scopes: []string{"login:email", "login:info", "login:avatar"},
|
||||
Endpoint: yandex.Endpoint,
|
||||
}
|
||||
|
||||
VKOAuthConfig = &oauth2.Config{
|
||||
ClientID: "your-vk-client-id",
|
||||
ClientSecret: "your-vk-client-secret",
|
||||
RedirectURL: "http://localhost:8080/auth/vk/callback",
|
||||
Scopes: []string{"email", "photos"},
|
||||
Endpoint: vk.Endpoint,
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,104 @@
|
||||
// handlers/auth.go
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"serv_golang_rest_api/internal/models"
|
||||
"serv_golang_rest_api/internal/utils"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
DB *gorm.DB
|
||||
}
|
||||
|
||||
type RegisterRequest struct {
|
||||
Email string `json:"email" validate:"required,email"`
|
||||
Password string `json:"password" validate:"required,min=6"`
|
||||
Name string `json:"name" validate:"required"`
|
||||
}
|
||||
|
||||
type LoginRequest struct {
|
||||
Email string `json:"email" validate:"required,email"`
|
||||
Password string `json:"password" validate:"required"`
|
||||
}
|
||||
|
||||
func (h *AuthHandler) Register(w http.ResponseWriter, r *http.Request) {
|
||||
var req RegisterRequest
|
||||
if err := utils.DecodeJSON(r, &req); err != nil {
|
||||
utils.WriteError(w, http.StatusBadRequest, "Invalid request")
|
||||
return
|
||||
}
|
||||
|
||||
// Проверяем, существует ли пользователь
|
||||
var existingUser models.User
|
||||
if err := h.DB.Where("email = ?", req.Email).First(&existingUser).Error; err == nil {
|
||||
utils.WriteError(w, http.StatusConflict, "User already exists")
|
||||
return
|
||||
}
|
||||
|
||||
// Хешируем пароль
|
||||
hashedPassword, err := utils.HashPassword(req.Password)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, "Error creating user")
|
||||
return
|
||||
}
|
||||
|
||||
// Создаем пользователя
|
||||
user := models.User{
|
||||
Email: req.Email,
|
||||
Password: hashedPassword,
|
||||
Name: req.Name,
|
||||
}
|
||||
|
||||
if err := h.DB.Create(&user).Error; err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, "Error creating user")
|
||||
return
|
||||
}
|
||||
|
||||
// Генерируем JWT токен
|
||||
token, err := utils.GenerateJWT(user.ID, user.Email)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, "Error generating token")
|
||||
return
|
||||
}
|
||||
|
||||
utils.WriteJSON(w, http.StatusCreated, map[string]interface{}{
|
||||
"token": token,
|
||||
"user": user,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
|
||||
var req LoginRequest
|
||||
if err := utils.DecodeJSON(r, &req); err != nil {
|
||||
utils.WriteError(w, http.StatusBadRequest, "Invalid request")
|
||||
return
|
||||
}
|
||||
|
||||
// Ищем пользователя
|
||||
var user models.User
|
||||
if err := h.DB.Where("email = ?", req.Email).First(&user).Error; err != nil {
|
||||
utils.WriteError(w, http.StatusUnauthorized, "Invalid credentials")
|
||||
return
|
||||
}
|
||||
|
||||
// Проверяем пароль
|
||||
if !utils.CheckPasswordHash(req.Password, user.Password) {
|
||||
utils.WriteError(w, http.StatusUnauthorized, "Invalid credentials")
|
||||
return
|
||||
}
|
||||
|
||||
// Генерируем JWT токен
|
||||
token, err := utils.GenerateJWT(user.ID, user.Email)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, "Error generating token")
|
||||
return
|
||||
}
|
||||
|
||||
utils.WriteJSON(w, http.StatusOK, map[string]interface{}{
|
||||
"token": token,
|
||||
"user": user,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/go-chi/cors"
|
||||
)
|
||||
|
||||
func CommonMiddleware() []func(http.Handler) http.Handler {
|
||||
return []func(http.Handler) http.Handler{
|
||||
middleware.Logger,
|
||||
middleware.Recoverer,
|
||||
middleware.Timeout(60 * time.Second),
|
||||
cors.Handler(cors.Options{
|
||||
AllowedOrigins: []string{"https://*", "http://*"},
|
||||
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
|
||||
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
|
||||
ExposedHeaders: []string{"Link"},
|
||||
AllowCredentials: false,
|
||||
MaxAge: 300,
|
||||
}),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
// handlers/oauth.go
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"serv_golang_rest_api/internal/config"
|
||||
"serv_golang_rest_api/internal/models"
|
||||
"serv_golang_rest_api/internal/utils"
|
||||
|
||||
"golang.org/x/oauth2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type OAuthHandler struct {
|
||||
DB *gorm.DB
|
||||
}
|
||||
|
||||
type GoogleUserInfo struct {
|
||||
ID string `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
|
||||
func (h *OAuthHandler) GoogleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
url := config.GoogleOAuthConfig.AuthCodeURL("state")
|
||||
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
|
||||
}
|
||||
|
||||
func (h *OAuthHandler) GoogleCallback(w http.ResponseWriter, r *http.Request) {
|
||||
code := r.URL.Query().Get("code")
|
||||
|
||||
token, err := config.GoogleOAuthConfig.Exchange(r.Context(), code)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusBadRequest, "Failed to exchange token")
|
||||
return
|
||||
}
|
||||
|
||||
client := config.GoogleOAuthConfig.Client(r.Context(), token)
|
||||
resp, err := client.Get("https://www.googleapis.com/oauth2/v2/userinfo")
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusBadRequest, "Failed to get user info")
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var userInfo GoogleUserInfo
|
||||
if err := json.NewDecoder(resp.Body).Decode(&userInfo); err != nil {
|
||||
utils.WriteError(w, http.StatusBadRequest, "Failed to decode user info")
|
||||
return
|
||||
}
|
||||
|
||||
// Создаем или находим пользователя
|
||||
user, err := h.findOrCreateOAuthUser("google", userInfo.ID, userInfo.Email, userInfo.Name, token)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, "Error processing user")
|
||||
return
|
||||
}
|
||||
|
||||
jwtToken, err := utils.GenerateJWT(user.ID, user.Email)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, "Error generating token")
|
||||
return
|
||||
}
|
||||
|
||||
// Редирект или возврат токена
|
||||
utils.WriteJSON(w, http.StatusOK, map[string]interface{}{
|
||||
"token": jwtToken,
|
||||
"user": user,
|
||||
})
|
||||
}
|
||||
|
||||
// Аналогичные методы для Yandex и VK...
|
||||
|
||||
func (h *OAuthHandler) findOrCreateOAuthUser(provider, providerID, email, name string, token *oauth2.Token) (*models.User, error) {
|
||||
var oauthProvider models.OAuthProvider
|
||||
|
||||
err := h.DB.Where("provider = ? AND provider_id = ?", provider, providerID).
|
||||
Preload("User").
|
||||
First(&oauthProvider).Error
|
||||
|
||||
if err == nil {
|
||||
// Обновляем токены существующей привязки
|
||||
oauthProvider.AccessToken = token.AccessToken
|
||||
oauthProvider.RefreshToken = token.RefreshToken
|
||||
oauthProvider.ExpiresAt = token.Expiry
|
||||
if err := h.DB.Save(&oauthProvider).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var user models.User
|
||||
if err := h.DB.First(&user, oauthProvider.UserID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// Ищем пользователя по email
|
||||
var user models.User
|
||||
err = h.DB.Where("email = ?", email).First(&user).Error
|
||||
|
||||
if err != nil {
|
||||
// Создаем нового пользователя
|
||||
user = models.User{
|
||||
Email: email,
|
||||
Name: name,
|
||||
Password: utils.GenerateRandomPassword(),
|
||||
}
|
||||
if err := h.DB.Create(&user).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// Создаем новую привязку OAuth с токенами
|
||||
oauthProvider = models.OAuthProvider{
|
||||
UserID: user.ID,
|
||||
Provider: provider,
|
||||
ProviderID: providerID,
|
||||
AccessToken: token.AccessToken,
|
||||
RefreshToken: token.RefreshToken,
|
||||
ExpiresAt: token.Expiry,
|
||||
}
|
||||
|
||||
if err := h.DB.Create(&oauthProvider).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"serv_golang_rest_api/internal/config"
|
||||
"serv_golang_rest_api/internal/utils"
|
||||
)
|
||||
|
||||
// VKUserInfo представляет данные пользователя от VK
|
||||
type VKUserInfo struct {
|
||||
Response []struct {
|
||||
ID int `json:"id"`
|
||||
FirstName string `json:"first_name"`
|
||||
LastName string `json:"last_name"`
|
||||
Email string `json:"email"`
|
||||
Photo string `json:"photo_200"`
|
||||
} `json:"response"`
|
||||
}
|
||||
|
||||
// VKEmailResponse представляет ответ с email от VK
|
||||
type VKEmailResponse struct {
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
// VKLogin initiates VK OAuth flow
|
||||
func (h *OAuthHandler) VKLogin(w http.ResponseWriter, r *http.Request) {
|
||||
url := config.VKOAuthConfig.AuthCodeURL("state")
|
||||
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
|
||||
}
|
||||
|
||||
// VKCallback handles VK OAuth callback
|
||||
func (h *OAuthHandler) VKCallback(w http.ResponseWriter, r *http.Request) {
|
||||
code := r.URL.Query().Get("code")
|
||||
|
||||
token, err := config.VKOAuthConfig.Exchange(r.Context(), code)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusBadRequest, "Failed to exchange token: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// VK не возвращает email в основном токене, нужно получить его отдельно
|
||||
email, err := h.getVKEmail(token.AccessToken)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusBadRequest, "Failed to get email from VK: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
client := config.VKOAuthConfig.Client(r.Context(), token)
|
||||
|
||||
// Получаем основную информацию о пользователе
|
||||
userInfoURL := fmt.Sprintf("https://api.vk.com/method/users.get?fields=photo_200,email&v=5.131&access_token=%s", token.AccessToken)
|
||||
resp, err := client.Get(userInfoURL)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusBadRequest, "Failed to get user info: "+err.Error())
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var vkUserInfo VKUserInfo
|
||||
if err := json.NewDecoder(resp.Body).Decode(&vkUserInfo); err != nil {
|
||||
utils.WriteError(w, http.StatusBadRequest, "Failed to decode user info: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if len(vkUserInfo.Response) == 0 {
|
||||
utils.WriteError(w, http.StatusBadRequest, "No user data received from VK")
|
||||
return
|
||||
}
|
||||
|
||||
vkUser := vkUserInfo.Response[0]
|
||||
userID := fmt.Sprintf("%d", vkUser.ID)
|
||||
name := vkUser.FirstName + " " + vkUser.LastName
|
||||
|
||||
// Используем email из отдельного запроса
|
||||
if email == "" && vkUser.Email != "" {
|
||||
email = vkUser.Email
|
||||
}
|
||||
|
||||
// Если email все еще пустой, создаем временный
|
||||
if email == "" {
|
||||
email = fmt.Sprintf("vk_%s@temp.vk", userID)
|
||||
}
|
||||
|
||||
// Создаем или находим пользователя
|
||||
user, err := h.findOrCreateOAuthUser("vk", userID, email, name, token)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, "Error processing user: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
jwtToken, err := utils.GenerateJWT(user.ID, user.Email)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, "Error generating token: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
h.handleOAuthSuccess(w, r, jwtToken, user)
|
||||
}
|
||||
|
||||
// getVKEmail получает email из VK OAuth
|
||||
func (h *OAuthHandler) getVKEmail(accessToken string) (string, error) {
|
||||
// VK возвращает email в ответе на запрос токена, но если его нет,
|
||||
// можно попробовать получить через API
|
||||
emailURL := fmt.Sprintf("https://api.vk.com/method/account.getProfileInfo?v=5.131&access_token=%s", accessToken)
|
||||
|
||||
resp, err := http.Get(emailURL)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var emailResp struct {
|
||||
Response struct {
|
||||
Email string `json:"email"`
|
||||
} `json:"response"`
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(resp.Body).Decode(&emailResp); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return emailResp.Response.Email, nil
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"serv_golang_rest_api/internal/config"
|
||||
"serv_golang_rest_api/internal/models"
|
||||
"serv_golang_rest_api/internal/utils"
|
||||
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
type YandexUserInfo struct {
|
||||
ID string `json:"id"`
|
||||
Login string `json:"login"`
|
||||
Email string `json:"default_email"`
|
||||
DisplayName string `json:"display_name"`
|
||||
FirstName string `json:"first_name"`
|
||||
LastName string `json:"last_name"`
|
||||
RealName string `json:"real_name"`
|
||||
DefaultEmail string `json:"default_email"`
|
||||
IsAvatarEmpty bool `json:"is_avatar_empty"`
|
||||
}
|
||||
|
||||
// YandexLogin initiates Yandex OAuth flow
|
||||
func (h *OAuthHandler) YandexLogin(w http.ResponseWriter, r *http.Request) {
|
||||
url := config.YandexOAuthConfig.AuthCodeURL("state", oauth2.AccessTypeOffline)
|
||||
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
|
||||
}
|
||||
|
||||
// YandexCallback handles Yandex OAuth callback
|
||||
func (h *OAuthHandler) YandexCallback(w http.ResponseWriter, r *http.Request) {
|
||||
code := r.URL.Query().Get("code")
|
||||
state := r.URL.Query().Get("state")
|
||||
|
||||
if state != "state" {
|
||||
utils.WriteError(w, http.StatusBadRequest, "Invalid state parameter")
|
||||
return
|
||||
}
|
||||
|
||||
token, err := config.YandexOAuthConfig.Exchange(r.Context(), code)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusBadRequest, "Failed to exchange token: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
client := config.YandexOAuthConfig.Client(r.Context(), token)
|
||||
|
||||
// Получаем информацию о пользователе
|
||||
resp, err := client.Get("https://login.yandex.ru/info?format=json")
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusBadRequest, "Failed to get user info: "+err.Error())
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var userInfo YandexUserInfo
|
||||
if err := json.NewDecoder(resp.Body).Decode(&userInfo); err != nil {
|
||||
utils.WriteError(w, http.StatusBadRequest, "Failed to decode user info: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Формируем имя пользователя
|
||||
name := h.getYandexUserName(userInfo)
|
||||
|
||||
// Создаем или находим пользователя
|
||||
user, err := h.findOrCreateOAuthUser("yandex", userInfo.ID, userInfo.DefaultEmail, name, token)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, "Error processing user: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
jwtToken, err := utils.GenerateJWT(user.ID, user.Email)
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusInternalServerError, "Error generating token: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
h.handleOAuthSuccess(w, r, jwtToken, user)
|
||||
}
|
||||
|
||||
func (h *OAuthHandler) handleOAuthSuccess(w http.ResponseWriter, r *http.Request, jwtToken string, user *models.User) {
|
||||
panic("unimplemented")
|
||||
}
|
||||
|
||||
// getYandexUserName формирует имя пользователя из данных Yandex
|
||||
func (h *OAuthHandler) getYandexUserName(userInfo YandexUserInfo) string {
|
||||
if userInfo.RealName != "" {
|
||||
return userInfo.RealName
|
||||
}
|
||||
if userInfo.DisplayName != "" {
|
||||
return userInfo.DisplayName
|
||||
}
|
||||
if userInfo.FirstName != "" && userInfo.LastName != "" {
|
||||
return userInfo.FirstName + " " + userInfo.LastName
|
||||
}
|
||||
if userInfo.FirstName != "" {
|
||||
return userInfo.FirstName
|
||||
}
|
||||
return userInfo.Login
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"serv_golang_rest_api/internal/models"
|
||||
"serv_golang_rest_api/internal/service"
|
||||
)
|
||||
|
||||
type UserHandler struct {
|
||||
userService *service.UserService
|
||||
}
|
||||
|
||||
func NewUserHandler(userService *service.UserService) *UserHandler {
|
||||
return &UserHandler{userService: userService}
|
||||
}
|
||||
|
||||
func (h *UserHandler) CreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
var req models.CreateUserRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.userService.CreateUser(&req)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(user)
|
||||
}
|
||||
|
||||
func (h *UserHandler) GetUser(w http.ResponseWriter, r *http.Request) {
|
||||
idStr := chi.URLParam(r, "id")
|
||||
id, err := strconv.ParseUint(idStr, 10, 32)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid user ID", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.userService.GetUserByID(uint(id))
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(user)
|
||||
}
|
||||
|
||||
func (h *UserHandler) GetAllUsers(w http.ResponseWriter, r *http.Request) {
|
||||
users, err := h.userService.GetAllUsers()
|
||||
if err != nil {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(users)
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// middleware/auth.go
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"serv_golang_rest_api/internal/utils"
|
||||
)
|
||||
|
||||
func AuthMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
authHeader := r.Header.Get("Authorization")
|
||||
if authHeader == "" {
|
||||
utils.WriteError(w, http.StatusUnauthorized, "Authorization header required")
|
||||
return
|
||||
}
|
||||
|
||||
parts := strings.Split(authHeader, " ")
|
||||
if len(parts) != 2 || parts[0] != "Bearer" {
|
||||
utils.WriteError(w, http.StatusUnauthorized, "Invalid authorization format")
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := utils.ValidateJWT(parts[1])
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusUnauthorized, "Invalid token")
|
||||
return
|
||||
}
|
||||
|
||||
// Добавляем claims в контекст
|
||||
ctx := context.WithValue(r.Context(), "userClaims", claims)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type OAuthProvider struct {
|
||||
ID uint `json:"id" gorm:"primaryKey"`
|
||||
UserID uint `json:"user_id" gorm:"not null;index"`
|
||||
Provider string `json:"provider" gorm:"not null;index"` // google, yandex, vk
|
||||
ProviderID string `json:"provider_id" gorm:"not null"` // ID пользователя в провайдере
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID uint `json:"id" gorm:"primarykey"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `json:"deleted_at,omitempty" gorm:"index"`
|
||||
|
||||
Name string `json:"name" gorm:"size:100;not null"`
|
||||
Email string `json:"email" gorm:"size:255;uniqueIndex;not null"`
|
||||
Password string `json:"-" gorm:"size:255;not null"` // Пароль не возвращаем в JSON
|
||||
// OAuth провайдеры
|
||||
OAuthProviders []OAuthProvider `json:"-"`
|
||||
}
|
||||
|
||||
type CreateUserRequest struct {
|
||||
Name string `json:"name" validate:"required,min=2,max=100"`
|
||||
Email string `json:"email" validate:"required,email"`
|
||||
Password string `json:"password" validate:"required,min=6"`
|
||||
}
|
||||
|
||||
type UpdateUserRequest struct {
|
||||
Name string `json:"name" validate:"omitempty,min=2,max=100"`
|
||||
Email string `json:"email" validate:"omitempty,email"`
|
||||
}
|
||||
|
||||
type UserResponse struct {
|
||||
ID uint `json:"id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"serv_golang_rest_api/internal/models"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type UserRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewUserRepository(db *gorm.DB) *UserRepository {
|
||||
return &UserRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *UserRepository) Create(user *models.User) error {
|
||||
return r.db.Create(user).Error
|
||||
}
|
||||
|
||||
func (r *UserRepository) FindByID(id uint) (*models.User, error) {
|
||||
var user models.User
|
||||
err := r.db.First(&user, id).Error
|
||||
return &user, err
|
||||
}
|
||||
|
||||
func (r *UserRepository) FindByEmail(email string) (*models.User, error) {
|
||||
var user models.User
|
||||
err := r.db.Where("email = ?", email).First(&user).Error
|
||||
return &user, err
|
||||
}
|
||||
|
||||
func (r *UserRepository) FindAll() ([]models.User, error) {
|
||||
var users []models.User
|
||||
err := r.db.Find(&users).Error
|
||||
return users, err
|
||||
}
|
||||
|
||||
func (r *UserRepository) Update(user *models.User) error {
|
||||
return r.db.Save(user).Error
|
||||
}
|
||||
|
||||
func (r *UserRepository) Delete(id uint) error {
|
||||
return r.db.Delete(&models.User{}, id).Error
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"serv_golang_rest_api/internal/handlers"
|
||||
"serv_golang_rest_api/internal/middleware"
|
||||
"serv_golang_rest_api/internal/repository"
|
||||
"serv_golang_rest_api/internal/service"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
router *chi.Mux
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func New(db *gorm.DB) *Server {
|
||||
s := &Server{
|
||||
router: chi.NewRouter(),
|
||||
db: db,
|
||||
}
|
||||
s.configureRouter(db)
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Server) configureRouter(db *gorm.DB) {
|
||||
// Общие middleware
|
||||
for _, middleware := range handlers.CommonMiddleware() {
|
||||
s.router.Use(middleware)
|
||||
}
|
||||
|
||||
// Health check
|
||||
s.router.Get("/health", s.healthCheck)
|
||||
|
||||
// API routes
|
||||
s.router.Route("/api/v1", func(r chi.Router) {
|
||||
s.setupUserRoutes(r, db)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) setupUserRoutes(r chi.Router, db *gorm.DB) {
|
||||
userRepo := repository.NewUserRepository(s.db)
|
||||
userService := service.NewUserService(userRepo)
|
||||
userHandler := handlers.NewUserHandler(userService)
|
||||
|
||||
authHandler := &handlers.AuthHandler{DB: db}
|
||||
oauthHandler := &handlers.OAuthHandler{DB: db}
|
||||
|
||||
// Публичные маршруты
|
||||
r.Route("/auth", func(r chi.Router) {
|
||||
r.Post("/register", authHandler.Register)
|
||||
r.Post("/login", authHandler.Login)
|
||||
|
||||
// OAuth routes
|
||||
r.Get("/google", oauthHandler.GoogleLogin)
|
||||
r.Get("/google/callback", oauthHandler.GoogleCallback)
|
||||
r.Get("/yandex", oauthHandler.YandexLogin)
|
||||
r.Get("/yandex/callback", oauthHandler.YandexCallback)
|
||||
r.Get("/vk", oauthHandler.VKLogin)
|
||||
r.Get("/vk/callback", oauthHandler.VKCallback)
|
||||
})
|
||||
|
||||
// Защищенные маршруты
|
||||
r.Route("/api", func(r chi.Router) {
|
||||
r.Use(middleware.AuthMiddleware)
|
||||
|
||||
r.Route("/users", func(r chi.Router) {
|
||||
r.Get("/", userHandler.GetAllUsers)
|
||||
r.Post("/", userHandler.CreateUser)
|
||||
r.Get("/{id}", userHandler.GetUser)
|
||||
})
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) healthCheck(w http.ResponseWriter, r *http.Request) {
|
||||
// Проверяем соединение с БД
|
||||
sqlDB, err := s.db.DB()
|
||||
if err != nil {
|
||||
http.Error(w, "Database connection error", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
|
||||
if err := sqlDB.Ping(); err != nil {
|
||||
http.Error(w, "Database ping failed", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"status": "healthy",
|
||||
"timestamp": http.TimeFormat,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) Run(port string) error {
|
||||
return http.ListenAndServe(":"+port, s.router)
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"serv_golang_rest_api/internal/models"
|
||||
"serv_golang_rest_api/internal/repository"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type UserService struct {
|
||||
userRepo *repository.UserRepository
|
||||
}
|
||||
|
||||
func NewUserService(userRepo *repository.UserRepository) *UserService {
|
||||
return &UserService{userRepo: userRepo}
|
||||
}
|
||||
|
||||
func (s *UserService) CreateUser(req *models.CreateUserRequest) (*models.UserResponse, error) {
|
||||
// Проверяем существует ли пользователь с таким email
|
||||
existingUser, err := s.userRepo.FindByEmail(req.Email)
|
||||
// Проверяем как на nil, так на пустой ID
|
||||
if existingUser != nil && existingUser.ID != 0 {
|
||||
return nil, errors.New("user with this email already exists")
|
||||
}
|
||||
|
||||
// Хешируем пароль
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
user := &models.User{
|
||||
Name: req.Name,
|
||||
Email: req.Email,
|
||||
Password: string(hashedPassword),
|
||||
}
|
||||
|
||||
if err := s.userRepo.Create(user); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.toUserResponse(user), nil
|
||||
}
|
||||
|
||||
func (s *UserService) GetUserByID(id uint) (*models.UserResponse, error) {
|
||||
user, err := s.userRepo.FindByID(id)
|
||||
if err != nil {
|
||||
return nil, errors.New("user not found")
|
||||
}
|
||||
|
||||
return s.toUserResponse(user), nil
|
||||
}
|
||||
|
||||
func (s *UserService) GetAllUsers() ([]models.UserResponse, error) {
|
||||
users, err := s.userRepo.FindAll()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var responses []models.UserResponse
|
||||
for _, user := range users {
|
||||
responses = append(responses, *s.toUserResponse(&user))
|
||||
}
|
||||
|
||||
return responses, nil
|
||||
}
|
||||
|
||||
func (s *UserService) toUserResponse(user *models.User) *models.UserResponse {
|
||||
return &models.UserResponse{
|
||||
ID: user.ID,
|
||||
CreatedAt: user.CreatedAt,
|
||||
UpdatedAt: user.UpdatedAt,
|
||||
Name: user.Name,
|
||||
Email: user.Email,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// utils/errors.go
|
||||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// APIError представляет ошибку API
|
||||
type APIError struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func (e *APIError) Error() string {
|
||||
return fmt.Sprintf("API Error %d: %s", e.Code, e.Message)
|
||||
}
|
||||
|
||||
// ErrorResponse представляет стандартный ответ с ошибкой
|
||||
type ErrorResponse struct {
|
||||
Error bool `json:"error"`
|
||||
Message string `json:"message"`
|
||||
Code int `json:"code"`
|
||||
}
|
||||
|
||||
// ValidationErrorResponse представляет ответ с ошибками валидации
|
||||
type ValidationErrorResponse struct {
|
||||
Error bool `json:"error"`
|
||||
Message string `json:"message"`
|
||||
Code int `json:"code"`
|
||||
Errors map[string]string `json:"errors,omitempty"`
|
||||
}
|
||||
|
||||
// Predefined errors
|
||||
var (
|
||||
ErrInvalidJSON = &APIError{Code: http.StatusBadRequest, Message: "Invalid JSON"}
|
||||
ErrEmptyRequestBody = &APIError{Code: http.StatusBadRequest, Message: "Request body is empty"}
|
||||
ErrRequestBodyTooLarge = &APIError{Code: http.StatusRequestEntityTooLarge, Message: "Request body too large"}
|
||||
)
|
||||
@@ -0,0 +1,115 @@
|
||||
// utils/json.go
|
||||
package utils
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// DecodeJSON декодирует JSON из тела запроса с валидацией
|
||||
func DecodeJSON(r *http.Request, v interface{}) error {
|
||||
// Ограничиваем размер тела запроса (например, 1MB)
|
||||
maxBytes := int64(1_048_576) // 1MB
|
||||
r.Body = http.MaxBytesReader(nil, r.Body, maxBytes)
|
||||
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields() // Запрещаем неизвестные поля
|
||||
|
||||
err := decoder.Decode(v)
|
||||
if err != nil {
|
||||
var syntaxError *json.SyntaxError
|
||||
var unmarshalTypeError *json.UnmarshalTypeError
|
||||
var invalidUnmarshalError *json.InvalidUnmarshalError
|
||||
|
||||
switch {
|
||||
case err == io.EOF:
|
||||
return &APIError{
|
||||
Code: http.StatusBadRequest,
|
||||
Message: "Request body is empty",
|
||||
}
|
||||
case err.Error() == "http: request body too large":
|
||||
return &APIError{
|
||||
Code: http.StatusRequestEntityTooLarge,
|
||||
Message: fmt.Sprintf("Request body must not be larger than %d bytes", maxBytes),
|
||||
}
|
||||
case strings.HasPrefix(err.Error(), "json: unknown field"):
|
||||
fieldName := strings.TrimPrefix(err.Error(), "json: unknown field ")
|
||||
return &APIError{
|
||||
Code: http.StatusBadRequest,
|
||||
Message: fmt.Sprintf("Unknown field in JSON: %s", fieldName),
|
||||
}
|
||||
case errors.As(err, &syntaxError):
|
||||
return &APIError{
|
||||
Code: http.StatusBadRequest,
|
||||
Message: fmt.Sprintf("Malformed JSON at position %d", syntaxError.Offset),
|
||||
}
|
||||
case errors.As(err, &unmarshalTypeError):
|
||||
return &APIError{
|
||||
Code: http.StatusBadRequest,
|
||||
Message: fmt.Sprintf("Invalid value for field '%s'. Expected type %s", unmarshalTypeError.Field, unmarshalTypeError.Type),
|
||||
}
|
||||
case errors.As(err, &invalidUnmarshalError):
|
||||
return &APIError{
|
||||
Code: http.StatusInternalServerError,
|
||||
Message: "Internal server error",
|
||||
}
|
||||
default:
|
||||
return &APIError{
|
||||
Code: http.StatusBadRequest,
|
||||
Message: "Invalid JSON",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Проверяем, что нет лишних данных после JSON
|
||||
if err = decoder.Decode(&struct{}{}); err != io.EOF {
|
||||
return &APIError{
|
||||
Code: http.StatusBadRequest,
|
||||
Message: "Request body must contain only single JSON object",
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// WriteJSON записывает JSON ответ
|
||||
func WriteJSON(w http.ResponseWriter, status int, data interface{}) error {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
|
||||
if data == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
encoder := json.NewEncoder(w)
|
||||
encoder.SetEscapeHTML(true) // Экранируем HTML для безопасности
|
||||
|
||||
return encoder.Encode(data)
|
||||
}
|
||||
|
||||
// WriteError записывает ошибку в формате JSON
|
||||
func WriteError(w http.ResponseWriter, status int, message string) {
|
||||
errorResponse := ErrorResponse{
|
||||
Error: true,
|
||||
Message: message,
|
||||
Code: status,
|
||||
}
|
||||
|
||||
WriteJSON(w, status, errorResponse)
|
||||
}
|
||||
|
||||
// WriteValidationError записывает ошибки валидации
|
||||
func WriteValidationError(w http.ResponseWriter, errors map[string]string) {
|
||||
errorResponse := ValidationErrorResponse{
|
||||
Error: true,
|
||||
Message: "Validation failed",
|
||||
Code: http.StatusBadRequest,
|
||||
Errors: errors,
|
||||
}
|
||||
|
||||
WriteJSON(w, http.StatusBadRequest, errorResponse)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
// utils/jwt.go
|
||||
package utils
|
||||
|
||||
import (
|
||||
"time"
|
||||
"github.com/golang-jwt/jwt/v4"
|
||||
)
|
||||
|
||||
var jwtSecret = []byte("your-secret-key") // вынеси в env variables
|
||||
|
||||
type Claims struct {
|
||||
UserID uint `json:"user_id"`
|
||||
Email string `json:"email"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
func GenerateJWT(userID uint, email string) (string, error) {
|
||||
expirationTime := time.Now().Add(24 * time.Hour)
|
||||
|
||||
claims := &Claims{
|
||||
UserID: userID,
|
||||
Email: email,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(expirationTime),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString(jwtSecret)
|
||||
}
|
||||
|
||||
func ValidateJWT(tokenString string) (*Claims, error) {
|
||||
claims := &Claims{}
|
||||
|
||||
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
|
||||
return jwtSecret, nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !token.Valid {
|
||||
return nil, jwt.ErrSignatureInvalid
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// utils/oauth_utils.go
|
||||
package utils
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"serv_golang_rest_api/internal/models"
|
||||
|
||||
"golang.org/x/oauth2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type OAuthHandler struct {
|
||||
DB *gorm.DB
|
||||
}
|
||||
|
||||
// GenerateState generates a random state string for OAuth
|
||||
func GenerateState() string {
|
||||
b := make([]byte, 16)
|
||||
rand.Read(b)
|
||||
return fmt.Sprintf("%x", b)
|
||||
}
|
||||
|
||||
func (h *OAuthHandler) findOrCreateOAuthUser(provider, providerID, email, name string, token *oauth2.Token) (*models.User, error) {
|
||||
var oauthProvider models.OAuthProvider
|
||||
|
||||
err := h.DB.Where("provider = ? AND provider_id = ?", provider, providerID).
|
||||
Preload("User").
|
||||
First(&oauthProvider).Error
|
||||
|
||||
if err == nil {
|
||||
// Обновляем токены существующей привязки
|
||||
oauthProvider.AccessToken = token.AccessToken
|
||||
oauthProvider.RefreshToken = token.RefreshToken
|
||||
oauthProvider.ExpiresAt = token.Expiry
|
||||
if err := h.DB.Save(&oauthProvider).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var user models.User
|
||||
if err := h.DB.First(&user, oauthProvider.UserID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// Ищем пользователя по email
|
||||
var user models.User
|
||||
err = h.DB.Where("email = ?", email).First(&user).Error
|
||||
|
||||
if err != nil {
|
||||
// Создаем нового пользователя
|
||||
user = models.User{
|
||||
Email: email,
|
||||
Name: name,
|
||||
Password: GenerateRandomPassword(),
|
||||
}
|
||||
if err := h.DB.Create(&user).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// Создаем новую привязку OAuth с токенами
|
||||
oauthProvider = models.OAuthProvider{
|
||||
UserID: user.ID,
|
||||
Provider: provider,
|
||||
ProviderID: providerID,
|
||||
AccessToken: token.AccessToken,
|
||||
RefreshToken: token.RefreshToken,
|
||||
ExpiresAt: token.Expiry,
|
||||
}
|
||||
|
||||
if err := h.DB.Create(&oauthProvider).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// utils/password.go
|
||||
package utils
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func HashPassword(password string) (string, error) {
|
||||
bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
return string(bytes), err
|
||||
}
|
||||
|
||||
func CheckPasswordHash(password, hash string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// GenerateRandomPassword генерирует случайный пароль для OAuth пользователей
|
||||
func GenerateRandomPassword() string {
|
||||
bytes := make([]byte, 32) // 256 бит
|
||||
_, err := rand.Read(bytes)
|
||||
if err != nil {
|
||||
// Fallback - используем временный пароль
|
||||
return "temp_oauth_password_123"
|
||||
}
|
||||
return base64.URLEncoding.EncodeToString(bytes)
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,16 @@
|
||||
-- Таблица пользователей
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(100) NOT NULL,
|
||||
email VARCHAR(255) UNIQUE NOT NULL,
|
||||
password VARCHAR(255) NOT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
deleted_at TIMESTAMP WITH TIME ZONE NULL
|
||||
);
|
||||
|
||||
-- Индекс для быстрого поиска по email
|
||||
CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
|
||||
|
||||
-- Индекс для мягкого удаления
|
||||
CREATE INDEX IF NOT EXISTS idx_users_deleted_at ON users(deleted_at);
|
||||
@@ -0,0 +1,52 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"serv_golang_rest_api/internal/config"
|
||||
"serv_golang_rest_api/internal/models"
|
||||
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func NewPostgresConnection(cfg *config.Config) (*gorm.DB, error) {
|
||||
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=UTC",
|
||||
cfg.DBHost, cfg.DBUser, cfg.DBPassword, cfg.DBName, cfg.DBPort)
|
||||
|
||||
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to connect to database: %w", err)
|
||||
}
|
||||
|
||||
// Автомиграция
|
||||
if err := autoMigrate(db); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
log.Println("Successfully connected to database")
|
||||
return db, nil
|
||||
}
|
||||
|
||||
func autoMigrate(db *gorm.DB) error {
|
||||
// Сначала добавляем колонку как NULLABLE
|
||||
if err := db.Exec(`ALTER TABLE users ADD COLUMN IF NOT EXISTS password VARCHAR(255)`).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Затем обновляем существующие записи (если нужно установить дефолтное значение)
|
||||
if err := db.Exec(`UPDATE users SET password = '' WHERE password IS NULL`).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// И только потом меняем на NOT NULL
|
||||
if err := db.Exec(`ALTER TABLE users ALTER COLUMN password SET NOT NULL`).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Или используйте автоматические миграции GORM
|
||||
return db.AutoMigrate(
|
||||
&models.User{},
|
||||
// другие модели...
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# FRONTEND SPA
|
||||
HTTP_INNER_PORT=80
|
||||
HTTP_OUTER_PORT=80
|
||||
HTTPS_INNER_PORT=443
|
||||
HTTPS_OUTER_PORT=443
|
||||
@@ -0,0 +1,8 @@
|
||||
services:
|
||||
spa:
|
||||
container_name: spa
|
||||
build:
|
||||
context: ./spa
|
||||
dockerfile: Dockerfile
|
||||
env_file:
|
||||
- .env
|
||||
@@ -0,0 +1,11 @@
|
||||
# Используем Node.js для сборки
|
||||
FROM node:18-alpine as builde
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Копируем package.json и package-lock.json для установки зависимостей
|
||||
COPY vue/package*.json ./
|
||||
|
||||
RUN npm install
|
||||
|
||||
copy ./vue .
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 11 KiB |
@@ -0,0 +1,135 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>ЯлАрба - Туристический агрегатор</title>
|
||||
<link rel="stylesheet" href="styles/mainStyle.css" />
|
||||
<link rel="icon" href="assets/bage_logo.png" type="img/png" />
|
||||
</head>
|
||||
<body>
|
||||
<!-- Yandex.Metrika counter -->
|
||||
<script type="text/javascript">
|
||||
(function (m, e, t, r, i, k, a) {
|
||||
m[i] =
|
||||
m[i] ||
|
||||
function () {
|
||||
(m[i].a = m[i].a || []).push(arguments);
|
||||
};
|
||||
m[i].l = 1 * new Date();
|
||||
for (var j = 0; j < document.scripts.length; j++) {
|
||||
if (document.scripts[j].src === r) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
(k = e.createElement(t)),
|
||||
(a = e.getElementsByTagName(t)[0]),
|
||||
(k.async = 1),
|
||||
(k.src = r),
|
||||
a.parentNode.insertBefore(k, a);
|
||||
})(
|
||||
window,
|
||||
document,
|
||||
"script",
|
||||
"https://mc.yandex.ru/metrika/tag.js",
|
||||
"ym"
|
||||
);
|
||||
|
||||
ym(103321366, "init", {
|
||||
clickmap: true,
|
||||
trackLinks: true,
|
||||
accurateTrackBounce: true,
|
||||
});
|
||||
</script>
|
||||
<noscript
|
||||
><div>
|
||||
<img
|
||||
src="https://mc.yandex.ru/watch/103321366"
|
||||
style="position: absolute; left: -9999px"
|
||||
alt="yandex metrika is disabled"
|
||||
/></div
|
||||
></noscript>
|
||||
<!-- /Yandex.Metrika counter -->
|
||||
|
||||
<header>
|
||||
<h1>ЯлАрба</h1>
|
||||
<p>Инновационный агрегатор мест отдыха с ИИ-планировщиком маршрутов</p>
|
||||
</header>
|
||||
|
||||
<section>
|
||||
<h2>О проекте</h2>
|
||||
<p>
|
||||
ЯлАрба — это супер-приложение для путешественников, объединяющее в себе:
|
||||
</p>
|
||||
<ul>
|
||||
<li>Агрегатор мест отдыха (отели, экскурсии, рестораны)</li>
|
||||
<li>Маркетплейс туров и локальных сувениров</li>
|
||||
<li>ИИ-планировщик маршрутов с учетом здоровья пользователя</li>
|
||||
<li>Систему бронирования и покупки билетов</li>
|
||||
</ul>
|
||||
<p>
|
||||
Наша миссия — сделать планирование путешествий простым,
|
||||
персонализированным и доступным.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<div class="developer">
|
||||
<h2>Разработчик</h2>
|
||||
<p><strong>Валитов Газиз</strong></p>
|
||||
<p>
|
||||
Full-stack разработчик с опытом в travel-tech проектах. Специализация:
|
||||
Python/Django, React, системы рекомендаций на основе ИИ.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<section class="roadmap">
|
||||
<h2>План разработки</h2>
|
||||
|
||||
<div class="phase">
|
||||
<h3>Этап 1: MVP (0-6 месяцев)</h3>
|
||||
<ul>
|
||||
<li>База мест отдыха (1000+ позиций)</li>
|
||||
<li>Интеграция с API бронирования (Booking.com, Ostrovok)</li>
|
||||
<li>Прототип ИИ-рекомендаций</li>
|
||||
<li>Мобильная версия (PWA)</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="phase">
|
||||
<h3>Этап 2: Монетизация (6-12 месяцев)</h3>
|
||||
<ul>
|
||||
<li>Система комиссий (10-15% с бронирований)</li>
|
||||
<li>Платные подписки (PRO-аккаунт)</li>
|
||||
<li>Партнерская программа для гидов</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="phase">
|
||||
<h3>Этап 3: Масштабирование (12-24 месяца)</h3>
|
||||
<ul>
|
||||
<li>Выход на рынки СНГ (Казахстан, Узбекистан)</li>
|
||||
<li>Полноценный ИИ-ассистент с рекомендациями по здоровью</li>
|
||||
<li>Интеграция с сервисами аренды авто</li>
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Технологический стек</h2>
|
||||
<ul>
|
||||
<li><strong>Frontend:</strong> React.js, TypeScript, PWA</li>
|
||||
<li><strong>Backend:</strong> Python/Django, PostgreSQL</li>
|
||||
<li>
|
||||
<strong>AI:</strong> NLP-модели для обработки запросов,
|
||||
рекомендательные системы
|
||||
</li>
|
||||
<li><strong>DevOps:</strong> Docker, Kubernetes, Yandex Cloud</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<footer>
|
||||
<p>© 2024 ЯлАрба. Все права защищены.</p>
|
||||
<p>Контакты: gaziz.valitov@yalarba.travel</p>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,53 @@
|
||||
body {
|
||||
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
|
||||
line-height: 1.6;
|
||||
color: #333;
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
background-color: #f5f7fa;
|
||||
}
|
||||
header {
|
||||
background-color: #1e88e5;
|
||||
color: white;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
margin-bottom: 30px;
|
||||
text-align: center;
|
||||
}
|
||||
h1 {
|
||||
margin: 0;
|
||||
font-size: 2.2em;
|
||||
}
|
||||
h2 {
|
||||
color: #1e88e5;
|
||||
border-bottom: 2px solid #1e88e5;
|
||||
padding-bottom: 5px;
|
||||
margin-top: 30px;
|
||||
}
|
||||
.developer {
|
||||
background-color: #e3f2fd;
|
||||
padding: 15px;
|
||||
border-radius: 8px;
|
||||
margin: 20px 0;
|
||||
}
|
||||
.roadmap {
|
||||
background-color: white;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
.phase {
|
||||
margin-bottom: 20px;
|
||||
padding-bottom: 20px;
|
||||
border-bottom: 1px dashed #ccc;
|
||||
}
|
||||
.phase:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
footer {
|
||||
text-align: center;
|
||||
margin-top: 40px;
|
||||
color: #666;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
### Есть задания для фрилансеров. Каждое задание 1000 рублей.
|
||||
|
||||
1. Задача настроить авторизацию через coocky no javaScript.
|
||||
2. Хранение состояния через vuex.
|
||||
3. Создать Makefile для работы со сборкой деплоем.
|
||||
|
||||
|
||||
## Project Setup
|
||||
|
||||
```sh
|
||||
npm install
|
||||
```
|
||||
|
||||
### Compile and Hot-Reload for Development
|
||||
|
||||
```sh
|
||||
npm run dev
|
||||
```
|
||||
|
||||
### Compile and Minify for Production
|
||||
|
||||
```sh
|
||||
npm run build
|
||||
```
|
||||
@@ -0,0 +1,30 @@
|
||||
Выбор шрифтов и размеров для мобильных устройств и десктопа зависит от множества факторов, таких как целевая аудитория, дизайн сайта/приложения и цели использования. Тем не менее, есть несколько общих рекомендаций, которые помогут обеспечить хорошую читаемость текста на разных устройствах.
|
||||
|
||||
### Шрифты
|
||||
|
||||
#### Для мобильных устройств:
|
||||
- **Roboto**: Один из самых популярных шрифтов для Android. Он имеет четкий и чистый вид, хорошо подходит для чтения на небольших экранах.
|
||||
- **San Francisco**: Стандартный шрифт для iOS. Хорошо сбалансирован и удобен для чтения.
|
||||
- **Open Sans**: Универсальный шрифт, который отлично смотрится на любых устройствах благодаря своей нейтральной стилистике.
|
||||
|
||||
#### Для десктопных устройств:
|
||||
- **Georgia**: Классический шрифт с засечками, который идеально подходит для длинных текстов. Обеспечивает комфортное чтение даже на больших экранах.
|
||||
- **Lato**: Современный шрифт без засечек, легкий и элегантный. Подходит для заголовков и основного текста.
|
||||
- **Merriweather**: Отличный выбор для длинных статей и блогов. Имеет хорошие пропорции и контрастность.
|
||||
|
||||
### Размеры шрифта
|
||||
|
||||
#### Мобильные устройства:
|
||||
- **Основной текст**: 16px–18px. Это оптимальный размер для комфортного чтения на маленьких экранах.
|
||||
- **Заголовки**: 20px–24px для h2, 18px–22px для h3, 16px–20px для h4.
|
||||
|
||||
#### Десктопные устройства:
|
||||
- **Основной текст**: 18px–20px. Такой размер обеспечивает удобство чтения на больших экранах.
|
||||
- **Заголовки**: 28px–32px для h2, 24px–28px для h3, 20px–24px для h4.
|
||||
|
||||
### Дополнительные советы:
|
||||
- Используйте **относительные единицы измерения** (em, rem) вместо абсолютных (px), чтобы шрифт масштабировался вместе с изменением размера экрана.
|
||||
- Следите за **межстрочным интервалом** (line-height). Оптимальное значение — около 1.5–1.6 для основного текста.
|
||||
- Убедитесь, что у вас достаточно **контраста между текстом и фоном**. Черный текст на белом фоне — классический пример хорошего сочетания.
|
||||
|
||||
Эти рекомендации помогут создать удобный интерфейс как для мобильных пользователей, так и для тех, кто работает за компьютером.
|
||||
@@ -0,0 +1,14 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<link rel="icon" href="/src/components/images/YalArbaLogo300.png">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<link rel="stylesheet" href="/src/assets/main.css">
|
||||
<title>YalArba</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
},
|
||||
},
|
||||
"exclude": ["node_modules", "dist"],
|
||||
}
|
||||
+4037
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "spa",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^1.7.9",
|
||||
"body-parser": "^1.20.3",
|
||||
"cors": "^2.8.5",
|
||||
"express": "^4.21.2",
|
||||
"jwt-decode": "^4.0.0",
|
||||
"pg": "^8.13.1",
|
||||
"pinia": "^2.3.1",
|
||||
"vue": "^3.5.13",
|
||||
"vue-i18n": "^11.1.0",
|
||||
"vue-material-design-icons": "^5.3.1",
|
||||
"vue-router": "^4.5.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
"vite": "^6.0.5",
|
||||
"vite-plugin-vue-devtools": "^7.6.8"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<script setup>
|
||||
import { RouterLink, RouterView } from 'vue-router'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="main">
|
||||
<RouterView />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
</style>
|
||||
@@ -0,0 +1,23 @@
|
||||
/* Светлая тема (по умолчанию) */
|
||||
:root {
|
||||
--background-color: #ffffff;
|
||||
--text-color: #1c1d1d;
|
||||
--light-dark-background-color: #ffffff;
|
||||
--light-dark-text-color: #273f2c;
|
||||
--disabled-backgroud-color: rgba(23, 62, 31, 0.281);
|
||||
--button-text-color: #bac677;
|
||||
--disabled-dark-background-color: rgba(55, 64, 62, 0.2);
|
||||
--button-dark-background-color: #3cbf40;
|
||||
--light-dark-background-color: #8cd68f;
|
||||
}
|
||||
|
||||
/* Темная тема */
|
||||
[data-theme="dark"] {
|
||||
--background-color: #282828;
|
||||
--text-color: #3cb756;
|
||||
--light-dark-background-color: #4e5e49;
|
||||
--light-dark-text-color: #59f37b;
|
||||
--disabled-dark-background-color: rgba(159, 193, 185, 0.2);
|
||||
--button-dark-background-color: #395e3a;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
@font-face {
|
||||
font-family: 'OpenSansVariableFont';
|
||||
src: url('./fonts/Open_Sans/hinted-OpenSans-Regular.ttf') format('truetype-variations'),
|
||||
url('./fonts/Open_Sans/OpenSans-Regular.woff') format('woff'),
|
||||
url('./fonts/Open_Sans/OpenSans-Regular.woff2') format('woff2');
|
||||
font-weight: 100 900;
|
||||
font-stretch: 50% 200%;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: 'OpenSansItalicVariableFont';
|
||||
src: url('./fonts/Open_Sans/hinted-OpenSans-Italic.ttf') format('truetype-variations'),
|
||||
url('./fonts/Open_Sans/OpenSans-Italic.woff') format('woff'),
|
||||
url('./fonts/Open_Sans/OpenSans-Italic.woff2') format('woff2');
|
||||
font-style: italic;
|
||||
font-weight: 100 900;
|
||||
font-stretch: 50% 200%;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: 'RobotoVariableFont';
|
||||
src: url('./fonts/Roboto/hinted-Roboto-Regular.ttf') format('truetype-variations'),
|
||||
url('./fonts/Roboto/Roboto-Regular.woff') format('woff'),
|
||||
url('./fonts/Roboto/Roboto-Regular.woff2') format('woff2');
|
||||
font-weight: 100 900;
|
||||
font-stretch: 50% 200%;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: 'RobotoItalicVarFont';
|
||||
src: url('./fonts/Roboto/hinted-Roboto-Italic.ttf') format('truetype-variations'),
|
||||
url('./fonts/Roboto/Roboto-Italic.woff') format('woff'),
|
||||
url('./fonts/Roboto/Roboto-Italic.woff2') format('woff2');
|
||||
font-style: italic;
|
||||
font-weight: 100 900;
|
||||
font-stretch: 50% 200%;
|
||||
}
|
||||
|
||||
:root {
|
||||
--font-primary: 'OpenSansVariableFont', Arial, sans-serif;
|
||||
--font-secondary: 'RobotoItalicVarFont', Arial, sans-serif;
|
||||
|
||||
--weight-light: 300;
|
||||
--weight-normal: 400;
|
||||
--weight-bold: 700;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: var(--font-primary);
|
||||
font-weight: var(--weight-normal);
|
||||
}
|
||||
|
||||
h1, h2, h3 {
|
||||
font-family: var(--font-secondary);
|
||||
font-weight: var(--weight-light);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
Copyright 2020 The Open Sans Project Authors (https://github.com/googlefonts/opensans)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://openfontlicense.org
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1,100 @@
|
||||
Open Sans Variable Font
|
||||
=======================
|
||||
|
||||
This download contains Open Sans as both variable fonts and static fonts.
|
||||
|
||||
Open Sans is a variable font with these axes:
|
||||
wdth
|
||||
wght
|
||||
|
||||
This means all the styles are contained in these files:
|
||||
OpenSans-VariableFont_wdth,wght.ttf
|
||||
OpenSans-Italic-VariableFont_wdth,wght.ttf
|
||||
|
||||
If your app fully supports variable fonts, you can now pick intermediate styles
|
||||
that aren’t available as static fonts. Not all apps support variable fonts, and
|
||||
in those cases you can use the static font files for Open Sans:
|
||||
static/OpenSans_Condensed-Light.ttf
|
||||
static/OpenSans_Condensed-Regular.ttf
|
||||
static/OpenSans_Condensed-Medium.ttf
|
||||
static/OpenSans_Condensed-SemiBold.ttf
|
||||
static/OpenSans_Condensed-Bold.ttf
|
||||
static/OpenSans_Condensed-ExtraBold.ttf
|
||||
static/OpenSans_SemiCondensed-Light.ttf
|
||||
static/OpenSans_SemiCondensed-Regular.ttf
|
||||
static/OpenSans_SemiCondensed-Medium.ttf
|
||||
static/OpenSans_SemiCondensed-SemiBold.ttf
|
||||
static/OpenSans_SemiCondensed-Bold.ttf
|
||||
static/OpenSans_SemiCondensed-ExtraBold.ttf
|
||||
static/OpenSans-Light.ttf
|
||||
static/OpenSans-Regular.ttf
|
||||
static/OpenSans-Medium.ttf
|
||||
static/OpenSans-SemiBold.ttf
|
||||
static/OpenSans-Bold.ttf
|
||||
static/OpenSans-ExtraBold.ttf
|
||||
static/OpenSans_Condensed-LightItalic.ttf
|
||||
static/OpenSans_Condensed-Italic.ttf
|
||||
static/OpenSans_Condensed-MediumItalic.ttf
|
||||
static/OpenSans_Condensed-SemiBoldItalic.ttf
|
||||
static/OpenSans_Condensed-BoldItalic.ttf
|
||||
static/OpenSans_Condensed-ExtraBoldItalic.ttf
|
||||
static/OpenSans_SemiCondensed-LightItalic.ttf
|
||||
static/OpenSans_SemiCondensed-Italic.ttf
|
||||
static/OpenSans_SemiCondensed-MediumItalic.ttf
|
||||
static/OpenSans_SemiCondensed-SemiBoldItalic.ttf
|
||||
static/OpenSans_SemiCondensed-BoldItalic.ttf
|
||||
static/OpenSans_SemiCondensed-ExtraBoldItalic.ttf
|
||||
static/OpenSans-LightItalic.ttf
|
||||
static/OpenSans-Italic.ttf
|
||||
static/OpenSans-MediumItalic.ttf
|
||||
static/OpenSans-SemiBoldItalic.ttf
|
||||
static/OpenSans-BoldItalic.ttf
|
||||
static/OpenSans-ExtraBoldItalic.ttf
|
||||
|
||||
Get started
|
||||
-----------
|
||||
|
||||
1. Install the font files you want to use
|
||||
|
||||
2. Use your app's font picker to view the font family and all the
|
||||
available styles
|
||||
|
||||
Learn more about variable fonts
|
||||
-------------------------------
|
||||
|
||||
https://developers.google.com/web/fundamentals/design-and-ux/typography/variable-fonts
|
||||
https://variablefonts.typenetwork.com
|
||||
https://medium.com/variable-fonts
|
||||
|
||||
In desktop apps
|
||||
|
||||
https://theblog.adobe.com/can-variable-fonts-illustrator-cc
|
||||
https://helpx.adobe.com/nz/photoshop/using/fonts.html#variable_fonts
|
||||
|
||||
Online
|
||||
|
||||
https://developers.google.com/fonts/docs/getting_started
|
||||
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Fonts/Variable_Fonts_Guide
|
||||
https://developer.microsoft.com/en-us/microsoft-edge/testdrive/demos/variable-fonts
|
||||
|
||||
Installing fonts
|
||||
|
||||
MacOS: https://support.apple.com/en-us/HT201749
|
||||
Linux: https://www.google.com/search?q=how+to+install+a+font+on+gnu%2Blinux
|
||||
Windows: https://support.microsoft.com/en-us/help/314960/how-to-install-or-remove-a-font-in-windows
|
||||
|
||||
Android Apps
|
||||
|
||||
https://developers.google.com/fonts/docs/android
|
||||
https://developer.android.com/guide/topics/ui/look-and-feel/downloadable-fonts
|
||||
|
||||
License
|
||||
-------
|
||||
Please read the full license text (OFL.txt) to understand the permissions,
|
||||
restrictions and requirements for usage, redistribution, and modification.
|
||||
|
||||
You can use them in your products & projects – print or digital,
|
||||
commercial or otherwise.
|
||||
|
||||
This isn't legal advice, please consider consulting a lawyer and see the full
|
||||
license for all details.
|
||||
Binary file not shown.
File diff suppressed because it is too large
Load Diff
|
After Width: | Height: | Size: 460 KiB |
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large
Load Diff
|
After Width: | Height: | Size: 406 KiB |
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user