Remake
Добавил авторизацию в приложение, сделал регистарцию, добавил мидлы
This commit is contained in:
@@ -1,51 +0,0 @@
|
|||||||
name: MRP Full Stack CI/CD
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [main, master]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
test-backend:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Checkout code
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v5 # Используем v5 (стабильнее)
|
|
||||||
with:
|
|
||||||
go-version: "1.24"
|
|
||||||
|
|
||||||
- name: Run Go tests
|
|
||||||
run: |
|
|
||||||
cd backend
|
|
||||||
go test ./... -v
|
|
||||||
|
|
||||||
test-frontend:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Checkout code
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Setup Node
|
|
||||||
uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version: 22
|
|
||||||
|
|
||||||
- name: Install & Build
|
|
||||||
run: |
|
|
||||||
cd frontend
|
|
||||||
npm install --legacy-peer-deps
|
|
||||||
npm run build
|
|
||||||
|
|
||||||
build-and-deploy:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: [test-backend, test-frontend]
|
|
||||||
steps:
|
|
||||||
- name: Checkout code
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Deploy full stack
|
|
||||||
run: |
|
|
||||||
# Мы не используем Buildx, так как работаем напрямую с Docker хоста
|
|
||||||
docker compose up -d --build --remove-orphans
|
|
||||||
@@ -46,3 +46,37 @@ func Login(c *gin.Context) {
|
|||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{"token": tokenString})
|
c.JSON(http.StatusOK, gin.H{"token": tokenString})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func Register(c *gin.Context) {
|
||||||
|
var input struct {
|
||||||
|
Username string `json:"username" binding:"required"`
|
||||||
|
Password string `json:"password" binding:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. Проверяем входящие данные
|
||||||
|
if err := c.ShouldBindJSON(&input); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid input"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Хешируем пароль (чтобы не хранить его в открытом виде)
|
||||||
|
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to hash password"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Создаем объект пользователя
|
||||||
|
user := models.User{
|
||||||
|
Username: input.Username,
|
||||||
|
Password: string(hashedPassword),
|
||||||
|
Role: "user", // по умолчанию
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Сохраняем в базу через GORM
|
||||||
|
if err := database.DB.Create(&user).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Could not create user maybe username exists?"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "Registration successful"})
|
||||||
|
}
|
||||||
|
|||||||
+17
-9
@@ -8,6 +8,7 @@ import (
|
|||||||
|
|
||||||
"viplight-mrp/database"
|
"viplight-mrp/database"
|
||||||
"viplight-mrp/handlers"
|
"viplight-mrp/handlers"
|
||||||
|
"viplight-mrp/middleware"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -24,7 +25,7 @@ func main() {
|
|||||||
r.Use(func(c *gin.Context) {
|
r.Use(func(c *gin.Context) {
|
||||||
c.Writer.Header().Set("Access-Control-Allow-Origin", "https://mrp.kkhome.ru")
|
c.Writer.Header().Set("Access-Control-Allow-Origin", "https://mrp.kkhome.ru")
|
||||||
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS")
|
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS")
|
||||||
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
||||||
if c.Request.Method == "OPTIONS" {
|
if c.Request.Method == "OPTIONS" {
|
||||||
c.AbortWithStatus(204)
|
c.AbortWithStatus(204)
|
||||||
return
|
return
|
||||||
@@ -32,14 +33,21 @@ func main() {
|
|||||||
c.Next()
|
c.Next()
|
||||||
})
|
})
|
||||||
|
|
||||||
// Роуты теперь вызывают функции из handlers
|
r.POST("/register", handlers.Register)
|
||||||
r.GET("/api/parts/:id", handlers.GetPart)
|
r.POST("/login", handlers.Login)
|
||||||
r.GET("/api/parts", handlers.GetAllParts)
|
|
||||||
r.GET("/api/orders", handlers.GetsOrders)
|
protected := r.Group("/api")
|
||||||
r.POST("/api/parts", handlers.CreatePart)
|
protected.Use(middleware.AuthRequired())
|
||||||
r.POST("/api/parts/bulk", handlers.ImportParts)
|
{
|
||||||
r.PATCH("/api/parts/:id/status", handlers.UpdateStatus)
|
protected.GET("/parts/:id", handlers.GetPart)
|
||||||
r.DELETE("/api/parts/:id", handlers.DeletePart)
|
protected.GET("/parts", handlers.GetAllParts)
|
||||||
|
protected.GET("/orders", handlers.GetsOrders)
|
||||||
|
protected.POST("/parts", handlers.CreatePart)
|
||||||
|
protected.POST("/parts/bulk", handlers.ImportParts)
|
||||||
|
protected.PATCH("/parts/:id/status", handlers.UpdateStatus)
|
||||||
|
protected.DELETE("/parts/:id", handlers.DeletePart)
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
r.Run(":8090")
|
r.Run(":8090")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/golang-jwt/jwt"
|
||||||
|
)
|
||||||
|
|
||||||
|
func AuthRequired() gin.HandlerFunc {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
authHeader := c.GetHeader("Authorization")
|
||||||
|
if authHeader == "" {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header is required"})
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
|
||||||
|
if tokenString == authHeader {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token format"})
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
jwtKey := []byte(os.Getenv("JWT_SECRET"))
|
||||||
|
|
||||||
|
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||||
|
return jwtKey, nil
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil || !token.Valid {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid or expired token"})
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
if claims, ok := token.Claims.(jwt.MapClaims); ok {
|
||||||
|
c.Set("user_id", claims["user_id"])
|
||||||
|
c.Set("role", claims["role"])
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,9 +13,26 @@ FROM nginx:stable-alpine
|
|||||||
|
|
||||||
COPY --from=build /app/dist /usr/share/nginx/html
|
COPY --from=build /app/dist /usr/share/nginx/html
|
||||||
|
|
||||||
|
|
||||||
COPY <<EOF /etc/nginx/conf.d/default.conf
|
COPY <<EOF /etc/nginx/conf.d/default.conf
|
||||||
server {
|
server {
|
||||||
listen 89;
|
listen 89;
|
||||||
|
|
||||||
|
location /register {
|
||||||
|
proxy_pass http://backend:8090;
|
||||||
|
proxy_set_header Host \$host;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /login {
|
||||||
|
proxy_pass http://backend:8090;
|
||||||
|
proxy_set_header Host \$host;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /api {
|
||||||
|
proxy_pass http://backend:8090;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Сама статика React
|
||||||
location / {
|
location / {
|
||||||
root /usr/share/nginx/html;
|
root /usr/share/nginx/html;
|
||||||
index index.html;
|
index index.html;
|
||||||
|
|||||||
+37
-4
@@ -1,15 +1,48 @@
|
|||||||
import { BrowserRouter, Routes, Route } from "react-router-dom";
|
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
|
||||||
import Dashboard from "./pages/Dashboard";
|
import Dashboard from "./pages/Dashboard";
|
||||||
import PartDetail from "./pages/PartDetail";
|
import PartDetail from "./pages/PartDetail";
|
||||||
import AddPartPage from "./pages/AddPartPage";
|
import AddPartPage from "./pages/AddPartPage";
|
||||||
|
import AuthForm from "./components/AuthForm";
|
||||||
|
|
||||||
|
const PrivateRoute = ({ children }) => {
|
||||||
|
const token = localStorage.getItem("token");
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
return <Navigate to="/login" replace />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return children;
|
||||||
|
};
|
||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
return (
|
return (
|
||||||
<BrowserRouter>
|
<BrowserRouter>
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route path="/" element={<Dashboard />} />
|
<Route path="/login" element={<AuthForm />} />
|
||||||
<Route path="/part/:id" element={<PartDetail />} />
|
<Route
|
||||||
<Route path="/add" element={<AddPartPage />} />
|
path="/"
|
||||||
|
element={
|
||||||
|
<PrivateRoute>
|
||||||
|
<Dashboard />
|
||||||
|
</PrivateRoute>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="/part/:id"
|
||||||
|
element={
|
||||||
|
<PrivateRoute>
|
||||||
|
<PartDetail />
|
||||||
|
</PrivateRoute>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="/add"
|
||||||
|
element={
|
||||||
|
<PrivateRoute>
|
||||||
|
<AddPartPage />
|
||||||
|
</PrivateRoute>
|
||||||
|
}
|
||||||
|
/>
|
||||||
</Routes>
|
</Routes>
|
||||||
</BrowserRouter>
|
</BrowserRouter>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -3,6 +3,30 @@ import Papa from "papaparse";
|
|||||||
|
|
||||||
const API_URL = "/api";
|
const API_URL = "/api";
|
||||||
|
|
||||||
|
axios.interceptors.request.use(
|
||||||
|
(config) => {
|
||||||
|
const token = localStorage.getItem("token");
|
||||||
|
if (token) {
|
||||||
|
config.headers.Authorization = `Bearer ${token}`;
|
||||||
|
}
|
||||||
|
return config;
|
||||||
|
},
|
||||||
|
(error) => {
|
||||||
|
return Promise.reject(error);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
axios.interceptors.response.use(
|
||||||
|
(response) => response,
|
||||||
|
(error) => {
|
||||||
|
if (error.response && error.response.status === 401) {
|
||||||
|
localStorage.removeItem("token");
|
||||||
|
window.location.href = "/login";
|
||||||
|
}
|
||||||
|
return Promise.reject(error);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
// Базовые CRUD операции
|
// Базовые CRUD операции
|
||||||
export const getAllParts = () => axios.get(`${API_URL}/parts`);
|
export const getAllParts = () => axios.get(`${API_URL}/parts`);
|
||||||
export const getAllOrders = () => axios.get(`${API_URL}/orders`);
|
export const getAllOrders = () => axios.get(`${API_URL}/orders`);
|
||||||
|
|||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import axios from "axios";
|
||||||
|
import { useNavigate } from "react-router-dom";
|
||||||
|
|
||||||
|
const AuthForm = () => {
|
||||||
|
const [isLogin, setIsLogin] = useState(true);
|
||||||
|
const [formData, setFormData] = useState({ username: "", password: "" });
|
||||||
|
const [message, setMessage] = useState({ text: "", isError: false });
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
const API_BASE = "";
|
||||||
|
|
||||||
|
const handleSubmit = async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setMessage({ text: "", isError: false });
|
||||||
|
|
||||||
|
const endpoint = isLogin ? "/login" : "/register";
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { data } = await axios.post(`${API_BASE}${endpoint}`, formData);
|
||||||
|
|
||||||
|
if (isLogin) {
|
||||||
|
localStorage.setItem("token", data.token);
|
||||||
|
navigate("/");
|
||||||
|
} else {
|
||||||
|
setMessage({
|
||||||
|
text: "Регистрация успешна! Теперь войдите",
|
||||||
|
isError: false,
|
||||||
|
});
|
||||||
|
setIsLogin(true);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
setMessage({
|
||||||
|
text: err.response?.data?.error || "Ошибка сервера",
|
||||||
|
isError: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen items-center justify-center bg-gray-100 px-4">
|
||||||
|
<div className="w-full max-w-md space-y-8 rounded-lg bg-white p-10 shadow-md">
|
||||||
|
<h2 className="text-center text-3xl font-bold text-gray-900">
|
||||||
|
{isLogin ? "Вход в MRP" : "Регистрация"}
|
||||||
|
</h2>
|
||||||
|
|
||||||
|
<form className="mt-8 space-y-6" onSubmit={handleSubmit}>
|
||||||
|
<div className="rounded-md shadow-sm -space-y-px">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
required
|
||||||
|
className="relative block w-full rounded-t-md border border-gray-300 px-3 py-2 text-gray-900 focus:z-10 focus:border-blue-500 focus:outline-none sm:text-sm"
|
||||||
|
placeholder="Логин"
|
||||||
|
onChange={(e) =>
|
||||||
|
setFormData({ ...formData, username: e.target.value })
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
required
|
||||||
|
className="relative block w-full rounded-b-md border border-gray-300 px-3 py-2 text-gray-900 focus:z-10 focus:border-blue-500 focus:outline-none sm:text-sm"
|
||||||
|
placeholder="Пароль"
|
||||||
|
onChange={(e) =>
|
||||||
|
setFormData({ ...formData, password: e.target.value })
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{message.text && (
|
||||||
|
<p
|
||||||
|
className={`text-sm ${message.isError ? "text-red-500" : "text-green-500"}`}
|
||||||
|
>
|
||||||
|
{message.text}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="group relative flex w-full justify-center rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 focus:outline-none"
|
||||||
|
>
|
||||||
|
{isLogin ? "Войти" : "Зарегистрироваться"}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div className="text-center">
|
||||||
|
<button
|
||||||
|
onClick={() => setIsLogin(!isLogin)}
|
||||||
|
className="text-sm text-blue-600 hover:text-blue-500"
|
||||||
|
>
|
||||||
|
{isLogin ? "Нет аккаунта? Создать" : "Уже есть аккаунт? Войти"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default AuthForm;
|
||||||
Reference in New Issue
Block a user