first commit
This commit is contained in:
parent
da69069e1b
commit
2c7e9caf45
|
|
@ -21,3 +21,8 @@
|
||||||
# Go workspace file
|
# Go workspace file
|
||||||
go.work
|
go.work
|
||||||
|
|
||||||
|
# ---> Node
|
||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
|
build/
|
||||||
|
|
||||||
|
|
|
||||||
Binary file not shown.
|
|
@ -0,0 +1,15 @@
|
||||||
|
# Server
|
||||||
|
PORT=3000
|
||||||
|
|
||||||
|
# Startup options
|
||||||
|
SEED=0
|
||||||
|
|
||||||
|
# Paths
|
||||||
|
CONFIG_PATH=configs/config.json
|
||||||
|
ROLES_CONFIG_PATH=configs/roles.json
|
||||||
|
FRONTEND_API_PATH=/Users/fabio/CODE/APP_GO_QUASAR/frontend/src/api
|
||||||
|
DB_driver=sqlite
|
||||||
|
DB_dsn=file:./data/data.db?_foreign_keys=on
|
||||||
|
|
||||||
|
# Auth
|
||||||
|
AUTH_SECRET=change-me
|
||||||
|
|
@ -0,0 +1,35 @@
|
||||||
|
{
|
||||||
|
"version": "0.2.0",
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"name": "Backend: Debug cmd/server",
|
||||||
|
"type": "go",
|
||||||
|
"request": "launch",
|
||||||
|
"mode": "debug",
|
||||||
|
"program": "${workspaceFolder}/cmd/server",
|
||||||
|
"cwd": "${workspaceFolder}",
|
||||||
|
"envFile": "${workspaceFolder}/.env",
|
||||||
|
"args": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Backend: Run cmd/server (no debug)",
|
||||||
|
"type": "go",
|
||||||
|
"request": "launch",
|
||||||
|
"mode": "debug",
|
||||||
|
"noDebug": true,
|
||||||
|
"program": "${workspaceFolder}/cmd/server",
|
||||||
|
"cwd": "${workspaceFolder}",
|
||||||
|
"envFile": "${workspaceFolder}/.env",
|
||||||
|
"args": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Backend: Attach to Delve :2345",
|
||||||
|
"type": "go",
|
||||||
|
"request": "attach",
|
||||||
|
"mode": "remote",
|
||||||
|
"host": "127.0.0.1",
|
||||||
|
"port": 2345,
|
||||||
|
"cwd": "${workspaceFolder}"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,483 @@
|
||||||
|
//
|
||||||
|
// Typescript API generated from gofiber backend
|
||||||
|
// Copyright (C) 2022 - 2025 Fabio Prada
|
||||||
|
//
|
||||||
|
// This file was generated by github.com/millevolte/ts-rpc
|
||||||
|
//
|
||||||
|
// Mar 15, 2026 16:33:29 UTC
|
||||||
|
//
|
||||||
|
|
||||||
|
export interface ApiRestResponse {
|
||||||
|
data?: unknown;
|
||||||
|
error: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isApiRestResponse(data: unknown): data is ApiRestResponse {
|
||||||
|
return (
|
||||||
|
typeof data === "object" &&
|
||||||
|
data !== null &&
|
||||||
|
Object.prototype.hasOwnProperty.call(data, "data") &&
|
||||||
|
Object.prototype.hasOwnProperty.call(data, "error")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeError(error: unknown): Error {
|
||||||
|
if (error instanceof DOMException && error.name === "AbortError") {
|
||||||
|
return new Error("api.error.timeouterror");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error instanceof TypeError && error.message === "Failed to fetch") {
|
||||||
|
return new Error("api.error.connectionerror");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error instanceof Error) {
|
||||||
|
return error;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Error(String(error));
|
||||||
|
}
|
||||||
|
|
||||||
|
export default class Api {
|
||||||
|
apiUrl: string;
|
||||||
|
localStorage: Storage | null;
|
||||||
|
|
||||||
|
constructor(apiurl: string) {
|
||||||
|
this.apiUrl = apiurl;
|
||||||
|
this.localStorage = window.localStorage;
|
||||||
|
}
|
||||||
|
|
||||||
|
async request(
|
||||||
|
method: string,
|
||||||
|
url: string,
|
||||||
|
data: unknown,
|
||||||
|
timeout = 7000,
|
||||||
|
upload = false,
|
||||||
|
): Promise<ApiRestResponse> {
|
||||||
|
const headers: { [key: string]: string } = {
|
||||||
|
"Cache-Control": "no-cache",
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!upload) {
|
||||||
|
headers["Content-Type"] = "application/json";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.localStorage) {
|
||||||
|
const auth = this.localStorage.getItem("Auth-Token");
|
||||||
|
if (auth) {
|
||||||
|
headers["Auth-Token"] = auth;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
||||||
|
const requestOptions: RequestInit = {
|
||||||
|
method,
|
||||||
|
cache: "no-store",
|
||||||
|
mode: "cors",
|
||||||
|
credentials: "include",
|
||||||
|
headers,
|
||||||
|
signal: controller.signal,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (upload) {
|
||||||
|
requestOptions.body = data as FormData;
|
||||||
|
} else if (data !== null && data !== undefined) {
|
||||||
|
requestOptions.body = JSON.stringify(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(url, requestOptions);
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("api.error." + response.statusText);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.localStorage) {
|
||||||
|
const jwt = response.headers.get("Auth-Token");
|
||||||
|
if (jwt) {
|
||||||
|
this.localStorage.setItem("Auth-Token", jwt);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const responseData = (await response.json()) as unknown;
|
||||||
|
if (!isApiRestResponse(responseData)) {
|
||||||
|
throw new Error("api.error.wrongdatatype");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (responseData.error) {
|
||||||
|
throw new Error(responseData.error);
|
||||||
|
}
|
||||||
|
|
||||||
|
return responseData;
|
||||||
|
} catch (error: unknown) {
|
||||||
|
throw normalizeError(error);
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timeoutId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
processResult(result: ApiRestResponse): {
|
||||||
|
data: unknown;
|
||||||
|
error: string | null;
|
||||||
|
} {
|
||||||
|
if (typeof result.data !== "object") {
|
||||||
|
return { data: result.data, error: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!result.data) {
|
||||||
|
result.data = {};
|
||||||
|
}
|
||||||
|
|
||||||
|
return { data: result.data, error: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
processError(error: unknown): {
|
||||||
|
data: unknown;
|
||||||
|
error: string | null;
|
||||||
|
} {
|
||||||
|
const normalizedError = normalizeError(error);
|
||||||
|
|
||||||
|
if (normalizedError.message === "api.error.timeouterror") {
|
||||||
|
Object.defineProperty(normalizedError, "__api_error__", {
|
||||||
|
value: normalizedError.message,
|
||||||
|
writable: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { data: null, error: normalizedError.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (normalizedError.message === "api.error.connectionerror") {
|
||||||
|
Object.defineProperty(normalizedError, "__api_error__", {
|
||||||
|
value: normalizedError.message,
|
||||||
|
writable: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { data: null, error: normalizedError.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
data: null,
|
||||||
|
error: normalizedError.message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async POST(
|
||||||
|
url: string,
|
||||||
|
data: unknown,
|
||||||
|
timeout?: number,
|
||||||
|
): Promise<{
|
||||||
|
data: unknown;
|
||||||
|
error: string | null;
|
||||||
|
}> {
|
||||||
|
try {
|
||||||
|
const upload = url.includes("/upload/");
|
||||||
|
const result = await this.request(
|
||||||
|
"POST",
|
||||||
|
this.apiUrl + url,
|
||||||
|
data,
|
||||||
|
timeout,
|
||||||
|
upload,
|
||||||
|
);
|
||||||
|
|
||||||
|
return this.processResult(result);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
return this.processError(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async GET(
|
||||||
|
url: string,
|
||||||
|
timeout?: number,
|
||||||
|
): Promise<{
|
||||||
|
data: unknown;
|
||||||
|
error: string | null;
|
||||||
|
}> {
|
||||||
|
try {
|
||||||
|
const result = await this.request(
|
||||||
|
"GET",
|
||||||
|
this.apiUrl + url,
|
||||||
|
null,
|
||||||
|
timeout,
|
||||||
|
);
|
||||||
|
return this.processResult(result);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
return this.processError(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async UPLOAD(
|
||||||
|
url: string,
|
||||||
|
data: unknown,
|
||||||
|
timeout?: number,
|
||||||
|
): Promise<{
|
||||||
|
data: unknown;
|
||||||
|
error: string | null;
|
||||||
|
}> {
|
||||||
|
try {
|
||||||
|
const result = await this.request(
|
||||||
|
"POST",
|
||||||
|
this.apiUrl + url,
|
||||||
|
data,
|
||||||
|
timeout,
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
|
||||||
|
return this.processResult(result);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
return this.processError(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const api = new Api("http://localhost:3000");
|
||||||
|
|
||||||
|
// Global Declarations
|
||||||
|
export type Nullable<T> = T | null;
|
||||||
|
|
||||||
|
export type Record<K extends string | number | symbol, T> = { [P in K]: T };
|
||||||
|
|
||||||
|
//
|
||||||
|
// package controllers
|
||||||
|
//
|
||||||
|
|
||||||
|
export interface LoginRequest {
|
||||||
|
username: string;
|
||||||
|
password: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RefreshRequest {
|
||||||
|
refresh_token: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SimpleResponse {
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ForgotPasswordRequest {
|
||||||
|
email: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ResetPasswordRequest {
|
||||||
|
token: string;
|
||||||
|
password: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ListUsersRequest {
|
||||||
|
page: number;
|
||||||
|
pageSize: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// package models
|
||||||
|
//
|
||||||
|
|
||||||
|
export interface UserPreferencesShort {
|
||||||
|
useIdle: boolean;
|
||||||
|
idleTimeout: number;
|
||||||
|
useIdlePassword: boolean;
|
||||||
|
idlePin: string;
|
||||||
|
useDirectLogin: boolean;
|
||||||
|
useQuadcodeLogin: boolean;
|
||||||
|
sendNoticesMail: boolean;
|
||||||
|
language: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UserShort {
|
||||||
|
email: string;
|
||||||
|
name: string;
|
||||||
|
roles: UserRoles;
|
||||||
|
status: UserStatus;
|
||||||
|
uuid: string;
|
||||||
|
details: Nullable<UserDetailsShort>;
|
||||||
|
preferences: Nullable<UserPreferencesShort>;
|
||||||
|
avatar: Nullable<string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UserCreateInput {
|
||||||
|
name: string;
|
||||||
|
email: string;
|
||||||
|
password: string;
|
||||||
|
roles: UserRoles;
|
||||||
|
status: UserStatus;
|
||||||
|
types: UserTypes;
|
||||||
|
avatar: Nullable<string>;
|
||||||
|
details: Nullable<UserDetailsShort>;
|
||||||
|
preferences: Nullable<UserPreferencesShort>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UserDetailsShort {
|
||||||
|
title: string;
|
||||||
|
firstName: string;
|
||||||
|
lastName: string;
|
||||||
|
address: string;
|
||||||
|
city: string;
|
||||||
|
zipCode: string;
|
||||||
|
country: string;
|
||||||
|
phone: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type UserRoles = string[];
|
||||||
|
|
||||||
|
export type UserStatus = (typeof EnumUserStatus)[keyof typeof EnumUserStatus];
|
||||||
|
|
||||||
|
export type UserTypes = string[];
|
||||||
|
|
||||||
|
export type UsersShort = UserShort[];
|
||||||
|
|
||||||
|
export const EnumUserStatus = {
|
||||||
|
UserStatusPending: "pending",
|
||||||
|
UserStatusActive: "active",
|
||||||
|
UserStatusDisabled: "disabled",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
//
|
||||||
|
// package routes
|
||||||
|
//
|
||||||
|
|
||||||
|
// Typescript: TSEndpoint= path=/auth/password/valid; name=validToken; method=POST; request=string; response=controllers.SimpleResponse
|
||||||
|
// internal/http/routes/auth_routes.go Line: 40
|
||||||
|
export const validToken = async (
|
||||||
|
data: string,
|
||||||
|
): Promise<{ data: SimpleResponse; error: Nullable<string> }> => {
|
||||||
|
return (await api.POST("/auth/password/valid", data)) as {
|
||||||
|
data: SimpleResponse;
|
||||||
|
error: Nullable<string>;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Typescript: TSEndpoint= path=/maildebug; name=mailDebug; method=GET; response=routes.[]MailDebugItem
|
||||||
|
// internal/http/routes/system_routes.go Line: 48
|
||||||
|
export const mailDebug = async (): Promise<{
|
||||||
|
data: MailDebugItem[];
|
||||||
|
error: Nullable<string>;
|
||||||
|
}> => {
|
||||||
|
return (await api.GET("/maildebug")) as {
|
||||||
|
data: MailDebugItem[];
|
||||||
|
error: Nullable<string>;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Typescript: TSEndpoint= path=/admin/users; name=listUsers; method=POST; request=controllers.ListUsersRequest; response=models.[]UserShort
|
||||||
|
// internal/http/routes/admin_routes.go Line: 12
|
||||||
|
export const listUsers = async (
|
||||||
|
data: ListUsersRequest,
|
||||||
|
): Promise<{ data: UserShort[]; error: Nullable<string> }> => {
|
||||||
|
return (await api.POST("/admin/users", data)) as {
|
||||||
|
data: UserShort[];
|
||||||
|
error: Nullable<string>;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Typescript: TSEndpoint= path=/auth/register; name=register; method=POST; request=models.UserCreateInput; response=models.UserShort
|
||||||
|
// internal/http/routes/auth_routes.go Line: 31
|
||||||
|
export const register = async (
|
||||||
|
data: UserCreateInput,
|
||||||
|
): Promise<{ data: UserShort; error: Nullable<string> }> => {
|
||||||
|
return (await api.POST("/auth/register", data)) as {
|
||||||
|
data: UserShort;
|
||||||
|
error: Nullable<string>;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Typescript: TSEndpoint= path=/metrics; name=metrics; method=GET; response=string
|
||||||
|
// internal/http/routes/system_routes.go Line: 37
|
||||||
|
export const metrics = async (): Promise<{
|
||||||
|
data: string;
|
||||||
|
error: Nullable<string>;
|
||||||
|
}> => {
|
||||||
|
return (await api.GET("/metrics")) as {
|
||||||
|
data: string;
|
||||||
|
error: Nullable<string>;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Typescript: TSEndpoint= path=/auth/login; name=login; method=POST; request=controllers.LoginRequest; response=auth.TokenPair
|
||||||
|
// internal/http/routes/auth_routes.go Line: 22
|
||||||
|
export const login = async (
|
||||||
|
data: LoginRequest,
|
||||||
|
): Promise<{ data: TokenPair; error: Nullable<string> }> => {
|
||||||
|
return (await api.POST("/auth/login", data)) as {
|
||||||
|
data: TokenPair;
|
||||||
|
error: Nullable<string>;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Typescript: TSEndpoint= path=/auth/refresh; name=refresh; method=POST; request=controllers.RefreshRequest; response=auth.TokenPair
|
||||||
|
// internal/http/routes/auth_routes.go Line: 25
|
||||||
|
export const refresh = async (
|
||||||
|
data: RefreshRequest,
|
||||||
|
): Promise<{ data: TokenPair; error: Nullable<string> }> => {
|
||||||
|
return (await api.POST("/auth/refresh", data)) as {
|
||||||
|
data: TokenPair;
|
||||||
|
error: Nullable<string>;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Typescript: TSEndpoint= path=/auth/password/forgot; name=forgotPassword; method=POST; request=controllers.ForgotPasswordRequest; response=controllers.SimpleResponse
|
||||||
|
// internal/http/routes/auth_routes.go Line: 34
|
||||||
|
export const forgotPassword = async (
|
||||||
|
data: ForgotPasswordRequest,
|
||||||
|
): Promise<{ data: SimpleResponse; error: Nullable<string> }> => {
|
||||||
|
return (await api.POST("/auth/password/forgot", data)) as {
|
||||||
|
data: SimpleResponse;
|
||||||
|
error: Nullable<string>;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Typescript: TSEndpoint= path=/auth/password/reset; name=resetPassword; method=POST; request=controllers.ResetPasswordRequest; response=controllers.SimpleResponse
|
||||||
|
// internal/http/routes/auth_routes.go Line: 37
|
||||||
|
export const resetPassword = async (
|
||||||
|
data: ResetPasswordRequest,
|
||||||
|
): Promise<{ data: SimpleResponse; error: Nullable<string> }> => {
|
||||||
|
return (await api.POST("/auth/password/reset", data)) as {
|
||||||
|
data: SimpleResponse;
|
||||||
|
error: Nullable<string>;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Typescript: TSEndpoint= path=/health; name=health; method=GET; response=string
|
||||||
|
// internal/http/routes/system_routes.go Line: 34
|
||||||
|
export const health = async (): Promise<{
|
||||||
|
data: string;
|
||||||
|
error: Nullable<string>;
|
||||||
|
}> => {
|
||||||
|
return (await api.GET("/health")) as {
|
||||||
|
data: string;
|
||||||
|
error: Nullable<string>;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Typescript: TSEndpoint= path=/auth/me; name=me; method=GET; response=models.UserShort
|
||||||
|
// internal/http/routes/auth_routes.go Line: 28
|
||||||
|
export const me = async (): Promise<{
|
||||||
|
data: UserShort;
|
||||||
|
error: Nullable<string>;
|
||||||
|
}> => {
|
||||||
|
return (await api.GET("/auth/me")) as {
|
||||||
|
data: UserShort;
|
||||||
|
error: Nullable<string>;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface FormRequest {
|
||||||
|
req: string;
|
||||||
|
count: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FormResponse {
|
||||||
|
test: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MailDebugItem {
|
||||||
|
name: string;
|
||||||
|
content: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// package auth
|
||||||
|
//
|
||||||
|
|
||||||
|
export interface TokenPair {
|
||||||
|
access_token: string;
|
||||||
|
refresh_token: string;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,223 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"flag"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"server/internal/auth"
|
||||||
|
"server/internal/config"
|
||||||
|
"server/internal/db"
|
||||||
|
"server/internal/http/controllers"
|
||||||
|
"server/internal/http/routes"
|
||||||
|
"server/internal/mail"
|
||||||
|
"server/internal/roles"
|
||||||
|
"server/internal/seed"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v3"
|
||||||
|
"github.com/gofiber/fiber/v3/middleware/cors"
|
||||||
|
"github.com/gofiber/fiber/v3/middleware/logger"
|
||||||
|
"github.com/gofiber/fiber/v3/middleware/recover"
|
||||||
|
"github.com/gofiber/fiber/v3/middleware/requestid"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Typescript: TSDeclaration= Nullable<T> = T | null;
|
||||||
|
// Typescript: TSDeclaration= Record<K extends string | number | symbol, T> = { [P in K]: T; }
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
loadDotEnv(".env")
|
||||||
|
|
||||||
|
seedCount := flag.Int("seed", 0, "seed N fake users at startup (0 to skip)")
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
configPath := envOrDefault("CONFIG_PATH", "configs/config.json")
|
||||||
|
cfg, err := config.LoadConfig(configPath)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("load config: %v", err)
|
||||||
|
}
|
||||||
|
if secret := os.Getenv("AUTH_SECRET"); secret != "" {
|
||||||
|
cfg.Auth.Secret = secret
|
||||||
|
}
|
||||||
|
|
||||||
|
dbCfg := db.Config{
|
||||||
|
Driver: envOrDefault("DB_driver", "sqlite"),
|
||||||
|
DSN: envOrDefault("DB_dsn", "file:./data/data.db?_foreign_keys=on"),
|
||||||
|
}
|
||||||
|
dbConn, err := db.Init(dbCfg)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("init db: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
authService, err := auth.New(auth.Config{
|
||||||
|
Secret: cfg.Auth.Secret,
|
||||||
|
Issuer: cfg.Auth.Issuer,
|
||||||
|
AccessTokenExpiry: time.Duration(cfg.Auth.AccessTokenExpiryMinutes) * time.Minute,
|
||||||
|
RefreshTokenExpiry: time.Duration(cfg.Auth.RefreshTokenExpiryMinutes) * time.Minute,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("setup auth: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
mailService, err := mail.New(mail.Config{
|
||||||
|
AppName: cfg.AppName,
|
||||||
|
Mode: cfg.Mail.Mode,
|
||||||
|
From: cfg.Mail.From,
|
||||||
|
DebugDir: cfg.Mail.DebugDir,
|
||||||
|
TemplatesDir: cfg.Mail.TemplatesDir,
|
||||||
|
FrontendBaseURL: cfg.Mail.FrontendBaseURL,
|
||||||
|
ResetPasswordPath: cfg.Mail.ResetPasswordPath,
|
||||||
|
SMTP: mail.SMTPConfig{
|
||||||
|
Host: cfg.Mail.SMTP.Host,
|
||||||
|
Port: cfg.Mail.SMTP.Port,
|
||||||
|
Username: cfg.Mail.SMTP.Username,
|
||||||
|
Password: cfg.Mail.SMTP.Password,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("setup mail: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
roleConfigPath := cfg.RolesConfigPath
|
||||||
|
if envRoleConfig := os.Getenv("ROLES_CONFIG_PATH"); envRoleConfig != "" {
|
||||||
|
roleConfigPath = envRoleConfig
|
||||||
|
}
|
||||||
|
if roleConfigPath == "" {
|
||||||
|
roleConfigPath = envOrDefault("ROLES_CONFIG_PATH", "configs/roles.json")
|
||||||
|
}
|
||||||
|
roleResolver, err := controllers.LoadRoleConfig(roleConfigPath)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("load role config: %v", err)
|
||||||
|
}
|
||||||
|
roles.CheckUserRoleConsistency(dbConn, roleResolver)
|
||||||
|
|
||||||
|
app := fiber.New(fiber.Config{
|
||||||
|
AppName: cfg.AppName,
|
||||||
|
ReadTimeout: time.Duration(cfg.ReadTimeoutSeconds) * time.Second,
|
||||||
|
WriteTimeout: time.Duration(cfg.WriteTimeoutSeconds) * time.Second,
|
||||||
|
IdleTimeout: time.Duration(cfg.IdleTimeoutSeconds) * time.Second,
|
||||||
|
ErrorHandler: func(c fiber.Ctx, err error) error {
|
||||||
|
code := fiber.StatusInternalServerError
|
||||||
|
msg := "internal server error"
|
||||||
|
if e, ok := err.(*fiber.Error); ok {
|
||||||
|
code = e.Code
|
||||||
|
msg = e.Message
|
||||||
|
}
|
||||||
|
reqID := requestid.FromContext(c)
|
||||||
|
log.Printf("error request_id=%s status=%d method=%s path=%s ip=%s ua=%q err=%v", reqID, code, c.Method(), c.Path(), c.IP(), c.Get("User-Agent"), err)
|
||||||
|
if code >= 500 {
|
||||||
|
msg = "internal server error"
|
||||||
|
}
|
||||||
|
return c.Status(code).JSON(fiber.Map{"data": nil, "error": msg})
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
app.Use(requestid.New())
|
||||||
|
app.Use(recover.New())
|
||||||
|
app.Use(logger.New())
|
||||||
|
app.Use(cors.New(cors.Config{
|
||||||
|
AllowOrigins: []string{"http://localhost:9000"},
|
||||||
|
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
|
||||||
|
AllowHeaders: []string{"Origin", "Auth-Token", "cache-control", "Content-Type", "Accept", "Authorization"},
|
||||||
|
AllowCredentials: true,
|
||||||
|
ExposeHeaders: []string{"Auth-Token"},
|
||||||
|
}))
|
||||||
|
|
||||||
|
app.Options("/*", func(c fiber.Ctx) error {
|
||||||
|
return c.SendStatus(fiber.StatusNoContent)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Make the DB handle available in request context for future handlers.
|
||||||
|
app.Use(func(c fiber.Ctx) error {
|
||||||
|
c.Locals("db", dbConn)
|
||||||
|
return c.Next()
|
||||||
|
})
|
||||||
|
|
||||||
|
app.Use(controllers.RequireEndpointPermission(roleResolver, authService))
|
||||||
|
routes.Register(app, authService, mailService)
|
||||||
|
|
||||||
|
port := envOrDefault("PORT", "3000")
|
||||||
|
|
||||||
|
seedToRun := *seedCount
|
||||||
|
if seedToRun <= 0 {
|
||||||
|
seedToRun = envIntOrDefault("SEED", 0)
|
||||||
|
}
|
||||||
|
if seedToRun > 0 {
|
||||||
|
_, creds, err := seed.SeedUsers(dbConn, seedToRun)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("seed users: %v", err)
|
||||||
|
}
|
||||||
|
for _, cred := range creds {
|
||||||
|
log.Printf("seeded user email=%s password=%s", cred.Email, cred.Password)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Graceful shutdown so ctrl+c or SIGTERM stops the server cleanly.
|
||||||
|
go func() {
|
||||||
|
if err := app.Listen(":" + port); err != nil {
|
||||||
|
log.Fatalf("server failed: %v", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
quit := make(chan os.Signal, 1)
|
||||||
|
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
||||||
|
<-quit
|
||||||
|
|
||||||
|
log.Println("Shutting down server...")
|
||||||
|
if err := app.Shutdown(); err != nil {
|
||||||
|
log.Printf("shutdown error: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func envOrDefault(key, fallback string) string {
|
||||||
|
if value := os.Getenv(key); value != "" {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
func envIntOrDefault(key string, fallback int) int {
|
||||||
|
value := os.Getenv(key)
|
||||||
|
if value == "" {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
parsed, err := strconv.Atoi(value)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("warning: invalid %s=%q, using default %d", key, value, fallback)
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
return parsed
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadDotEnv(path string) {
|
||||||
|
file, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
scanner := bufio.NewScanner(file)
|
||||||
|
for scanner.Scan() {
|
||||||
|
line := strings.TrimSpace(scanner.Text())
|
||||||
|
if line == "" || strings.HasPrefix(line, "#") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
parts := strings.SplitN(line, "=", 2)
|
||||||
|
if len(parts) != 2 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
key := strings.TrimSpace(parts[0])
|
||||||
|
value := strings.TrimSpace(parts[1])
|
||||||
|
if key == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, exists := os.LookupEnv(key); !exists {
|
||||||
|
_ = os.Setenv(key, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,27 @@
|
||||||
|
{
|
||||||
|
"app_name": "Fiber Starter",
|
||||||
|
"read_timeout_seconds": 5,
|
||||||
|
"write_timeout_seconds": 10,
|
||||||
|
"idle_timeout_seconds": 30,
|
||||||
|
"disable_startup_message": false,
|
||||||
|
"auth": {
|
||||||
|
"secret": "change-me",
|
||||||
|
"issuer": "fiber-starter",
|
||||||
|
"access_token_expiry_minutes": 60,
|
||||||
|
"refresh_token_expiry_minutes": 4320
|
||||||
|
},
|
||||||
|
"mail": {
|
||||||
|
"mode": "file",
|
||||||
|
"from": "noreply@example.local",
|
||||||
|
"debug_dir": "data/mail-debug",
|
||||||
|
"templates_dir": "internal/http/templates",
|
||||||
|
"frontend_base_url": "http://localhost:9000",
|
||||||
|
"reset_password_path": "/#reset-password",
|
||||||
|
"smtp": {
|
||||||
|
"host": "",
|
||||||
|
"port": 587,
|
||||||
|
"username": "",
|
||||||
|
"password": ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,22 @@
|
||||||
|
{
|
||||||
|
"roles": {
|
||||||
|
"admin": ["admin", "manager", "user"],
|
||||||
|
"manager": ["manager", "user"],
|
||||||
|
"user": ["user"]
|
||||||
|
},
|
||||||
|
"permissions": {
|
||||||
|
"admin": [
|
||||||
|
"users:read",
|
||||||
|
"users:write",
|
||||||
|
"sessions:purge",
|
||||||
|
"admin:users:list"
|
||||||
|
],
|
||||||
|
"manager": [
|
||||||
|
"users:read"
|
||||||
|
],
|
||||||
|
"user": []
|
||||||
|
},
|
||||||
|
"endpoints": {
|
||||||
|
"POST /admin/users": "admin:users:list"
|
||||||
|
}
|
||||||
|
}
|
||||||
Binary file not shown.
|
|
@ -0,0 +1,56 @@
|
||||||
|
module server
|
||||||
|
|
||||||
|
go 1.25.4
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/brianvoe/gofakeit/v6 v6.28.0
|
||||||
|
github.com/go-playground/validator/v10 v10.30.1
|
||||||
|
github.com/gofiber/fiber/v3 v3.1.0
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||||
|
github.com/google/uuid v1.6.0
|
||||||
|
github.com/prometheus/client_golang v1.23.2
|
||||||
|
golang.org/x/crypto v0.48.0
|
||||||
|
gorm.io/driver/postgres v1.6.0
|
||||||
|
gorm.io/driver/sqlite v1.6.0
|
||||||
|
gorm.io/gorm v1.31.1
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/andybalholm/brotli v1.2.0 // indirect
|
||||||
|
github.com/beorn7/perks v1.0.1 // indirect
|
||||||
|
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||||
|
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
|
||||||
|
github.com/go-playground/locales v0.14.1 // indirect
|
||||||
|
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||||
|
github.com/gofiber/schema v1.7.0 // indirect
|
||||||
|
github.com/gofiber/utils/v2 v2.0.2 // indirect
|
||||||
|
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
|
||||||
|
github.com/klauspost/compress v1.18.4 // indirect
|
||||||
|
github.com/kr/text v0.2.0 // indirect
|
||||||
|
github.com/leodido/go-urn v1.4.0 // indirect
|
||||||
|
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||||
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
|
github.com/mattn/go-runewidth v0.0.16 // indirect
|
||||||
|
github.com/mattn/go-sqlite3 v1.14.22 // indirect
|
||||||
|
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||||
|
github.com/philhofer/fwd v1.2.0 // indirect
|
||||||
|
github.com/prometheus/client_model v0.6.2 // indirect
|
||||||
|
github.com/prometheus/common v0.66.1 // indirect
|
||||||
|
github.com/prometheus/procfs v0.16.1 // indirect
|
||||||
|
github.com/rivo/uniseg v0.2.0 // indirect
|
||||||
|
github.com/tinylib/msgp v1.6.3 // indirect
|
||||||
|
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||||
|
github.com/valyala/fasthttp v1.69.0 // indirect
|
||||||
|
github.com/valyala/tcplisten v1.0.0 // indirect
|
||||||
|
go.yaml.in/yaml/v2 v2.4.2 // indirect
|
||||||
|
golang.org/x/net v0.50.0 // indirect
|
||||||
|
golang.org/x/sync v0.19.0 // indirect
|
||||||
|
golang.org/x/sys v0.41.0 // indirect
|
||||||
|
golang.org/x/text v0.34.0 // indirect
|
||||||
|
google.golang.org/protobuf v1.36.8 // indirect
|
||||||
|
)
|
||||||
|
|
@ -0,0 +1,140 @@
|
||||||
|
github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M=
|
||||||
|
github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY=
|
||||||
|
github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ=
|
||||||
|
github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
||||||
|
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||||
|
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||||
|
github.com/brianvoe/gofakeit/v6 v6.28.0 h1:Xib46XXuQfmlLS2EXRuJpqcw8St6qSZz75OUo0tgAW4=
|
||||||
|
github.com/brianvoe/gofakeit/v6 v6.28.0/go.mod h1:Xj58BMSnFqcn/fAQeSK+/PLtC5kSb7FJIq4JyGa8vEs=
|
||||||
|
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||||
|
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
|
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||||
|
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/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
|
||||||
|
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||||
|
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||||
|
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||||
|
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||||
|
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||||
|
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||||
|
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||||
|
github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
|
||||||
|
github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
|
||||||
|
github.com/gofiber/fiber/v2 v2.52.12 h1:0LdToKclcPOj8PktUdIKo9BUohjjwfnQl42Dhw8/WUw=
|
||||||
|
github.com/gofiber/fiber/v2 v2.52.12/go.mod h1:YEcBbO/FB+5M1IZNBP9FO3J9281zgPAreiI1oqg8nDw=
|
||||||
|
github.com/gofiber/fiber/v3 v3.1.0 h1:1p4I820pIa+FGxfwWuQZ5rAyX0WlGZbGT6Hnuxt6hKY=
|
||||||
|
github.com/gofiber/fiber/v3 v3.1.0/go.mod h1:n2nYQovvL9z3Too/FGOfgtERjW3GQcAUqgfoezGBZdU=
|
||||||
|
github.com/gofiber/schema v1.7.0 h1:yNM+FNRZjyYEli9Ey0AXRBrAY9jTnb+kmGs3lJGPvKg=
|
||||||
|
github.com/gofiber/schema v1.7.0/go.mod h1:A/X5Ffyru4p9eBdp99qu+nzviHzQiZ7odLT+TwxWhbk=
|
||||||
|
github.com/gofiber/utils/v2 v2.0.2 h1:ShRRssz0F3AhTlAQcuEj54OEDtWF7+HJDwEi/aa6QLI=
|
||||||
|
github.com/gofiber/utils/v2 v2.0.2/go.mod h1:+9Ub4NqQ+IaJoTliq5LfdmOJAA/Hzwf4pXOxOa3RrJ0=
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||||
|
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||||
|
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||||
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
|
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/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
|
||||||
|
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
|
||||||
|
github.com/klauspost/compress v1.18.4 h1:RPhnKRAQ4Fh8zU2FY/6ZFDwTVTxgJ/EMydqSTzE9a2c=
|
||||||
|
github.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
|
||||||
|
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||||
|
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||||
|
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||||
|
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||||
|
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
||||||
|
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
||||||
|
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||||
|
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||||
|
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||||
|
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||||
|
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||||
|
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||||
|
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||||
|
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||||
|
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||||
|
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
|
||||||
|
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||||
|
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||||
|
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||||
|
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||||
|
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||||
|
github.com/philhofer/fwd v1.1.3-0.20240916144458-20a13a1f6b7c h1:dAMKvw0MlJT1GshSTtih8C2gDs04w8dReiOGXrGLNoY=
|
||||||
|
github.com/philhofer/fwd v1.1.3-0.20240916144458-20a13a1f6b7c/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
|
||||||
|
github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM=
|
||||||
|
github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
|
||||||
|
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/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
|
||||||
|
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
|
||||||
|
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
|
||||||
|
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
|
||||||
|
github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs=
|
||||||
|
github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA=
|
||||||
|
github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg=
|
||||||
|
github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is=
|
||||||
|
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
|
||||||
|
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||||
|
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
|
||||||
|
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
|
||||||
|
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.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
|
github.com/tinylib/msgp v1.2.5 h1:WeQg1whrXRFiZusidTQqzETkRpGjFjcIhW6uqWH09po=
|
||||||
|
github.com/tinylib/msgp v1.2.5/go.mod h1:ykjzy2wzgrlvpDCRc4LA8UXy6D8bzMSuAF3WD57Gok0=
|
||||||
|
github.com/tinylib/msgp v1.6.3 h1:bCSxiTz386UTgyT1i0MSCvdbWjVW+8sG3PjkGsZQt4s=
|
||||||
|
github.com/tinylib/msgp v1.6.3/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA=
|
||||||
|
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||||
|
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||||
|
github.com/valyala/fasthttp v1.51.0 h1:8b30A5JlZ6C7AS81RsWjYMQmrZG6feChmgAolCl1SqA=
|
||||||
|
github.com/valyala/fasthttp v1.51.0/go.mod h1:oI2XroL+lI7vdXyYoQk03bXBThfFl2cVdIA3Xl7cH8g=
|
||||||
|
github.com/valyala/fasthttp v1.69.0 h1:fNLLESD2SooWeh2cidsuFtOcrEi4uB4m1mPrkJMZyVI=
|
||||||
|
github.com/valyala/fasthttp v1.69.0/go.mod h1:4wA4PfAraPlAsJ5jMSqCE2ug5tqUPwKXxVj8oNECGcw=
|
||||||
|
github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8=
|
||||||
|
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
|
||||||
|
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||||
|
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||||
|
go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI=
|
||||||
|
go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=
|
||||||
|
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
|
||||||
|
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
|
||||||
|
golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60=
|
||||||
|
golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM=
|
||||||
|
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||||
|
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||||
|
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
|
||||||
|
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||||
|
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
|
||||||
|
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
|
||||||
|
google.golang.org/protobuf v1.36.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc=
|
||||||
|
google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||||
|
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/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
|
||||||
|
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
|
||||||
|
gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg=
|
||||||
|
gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
|
||||||
|
|
@ -0,0 +1,29 @@
|
||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// HashPassword returns the bcrypt hash for the given password using the default cost.
|
||||||
|
func HashPassword(password string) (string, error) {
|
||||||
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("hash password: %w", err)
|
||||||
|
}
|
||||||
|
return string(hash), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// VerifyPassword compares a bcrypt hash and a plaintext password in constant time.
|
||||||
|
func VerifyPassword(hashedPassword, password string) (bool, error) {
|
||||||
|
err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
|
||||||
|
if err == nil {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
return false, fmt.Errorf("compare password: %w", err)
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,187 @@
|
||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v3"
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
Secret string
|
||||||
|
Issuer string
|
||||||
|
AccessTokenExpiry time.Duration
|
||||||
|
RefreshTokenExpiry time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
type Service struct {
|
||||||
|
cfg Config
|
||||||
|
secret []byte
|
||||||
|
accessExpiry time.Duration
|
||||||
|
refreshExpiry time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
type Claims struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
TokenType string `json:"type"`
|
||||||
|
jwt.RegisteredClaims
|
||||||
|
}
|
||||||
|
|
||||||
|
// Typescript: interface
|
||||||
|
type TokenPair struct {
|
||||||
|
AccessToken string `json:"access_token"`
|
||||||
|
RefreshToken string `json:"refresh_token"`
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
tokenTypeAccess = "access"
|
||||||
|
tokenTypeRefresh = "refresh"
|
||||||
|
)
|
||||||
|
|
||||||
|
func New(cfg Config) (*Service, error) {
|
||||||
|
if cfg.Secret == "" {
|
||||||
|
return nil, errors.New("jwt secret is required")
|
||||||
|
}
|
||||||
|
if cfg.AccessTokenExpiry <= 0 {
|
||||||
|
return nil, errors.New("access token expiry must be positive")
|
||||||
|
}
|
||||||
|
if cfg.RefreshTokenExpiry <= 0 {
|
||||||
|
return nil, errors.New("refresh token expiry must be positive")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Service{
|
||||||
|
cfg: cfg,
|
||||||
|
secret: []byte(cfg.Secret),
|
||||||
|
accessExpiry: cfg.AccessTokenExpiry,
|
||||||
|
refreshExpiry: cfg.RefreshTokenExpiry,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GenerateTokenPair(username string) (TokenPair, error) {
|
||||||
|
access, err := s.generateToken(username, tokenTypeAccess, s.accessExpiry)
|
||||||
|
if err != nil {
|
||||||
|
return TokenPair{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
refresh, err := s.generateToken(username, tokenTypeRefresh, s.refreshExpiry)
|
||||||
|
if err != nil {
|
||||||
|
return TokenPair{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return TokenPair{
|
||||||
|
AccessToken: access,
|
||||||
|
RefreshToken: refresh,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// AccessExpiry returns the configured access token lifetime.
|
||||||
|
func (s *Service) AccessExpiry() time.Duration {
|
||||||
|
return s.accessExpiry
|
||||||
|
}
|
||||||
|
|
||||||
|
// RefreshExpiry returns the configured refresh token lifetime.
|
||||||
|
func (s *Service) RefreshExpiry() time.Duration {
|
||||||
|
return s.refreshExpiry
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) Middleware() fiber.Handler {
|
||||||
|
return func(c fiber.Ctx) error {
|
||||||
|
tokenString := c.Get("Auth-Token")
|
||||||
|
if tokenString == "" {
|
||||||
|
return fiber.NewError(fiber.StatusUnauthorized, "missing token header")
|
||||||
|
}
|
||||||
|
|
||||||
|
claims, err := s.parseToken(tokenString)
|
||||||
|
if err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusUnauthorized, err.Error())
|
||||||
|
}
|
||||||
|
if claims.TokenType != tokenTypeAccess {
|
||||||
|
return fiber.NewError(fiber.StatusUnauthorized, "access token required")
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Locals("authClaims", claims)
|
||||||
|
return c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) Refresh(refreshToken string) (TokenPair, error) {
|
||||||
|
claims, err := s.parseToken(refreshToken)
|
||||||
|
if err != nil {
|
||||||
|
return TokenPair{}, err
|
||||||
|
}
|
||||||
|
if claims.TokenType != tokenTypeRefresh {
|
||||||
|
return TokenPair{}, errors.New("refresh token required")
|
||||||
|
}
|
||||||
|
return s.GenerateTokenPair(claims.Username)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateAccessToken parses and validates an access token string, ensuring type=access.
|
||||||
|
func (s *Service) ValidateAccessToken(tokenString string) (*Claims, error) {
|
||||||
|
claims, err := s.parseToken(tokenString)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if claims.TokenType != tokenTypeAccess {
|
||||||
|
return nil, errors.New("access token required")
|
||||||
|
}
|
||||||
|
return claims, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) parseToken(tokenString string) (*Claims, error) {
|
||||||
|
claims := &Claims{}
|
||||||
|
token, err := jwt.ParseWithClaims(tokenString, claims, func(t *jwt.Token) (interface{}, error) {
|
||||||
|
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||||
|
return nil, fiber.ErrUnauthorized
|
||||||
|
}
|
||||||
|
return s.secret, nil
|
||||||
|
})
|
||||||
|
if err != nil || !token.Valid {
|
||||||
|
return nil, errors.New("invalid or expired token")
|
||||||
|
}
|
||||||
|
if s.cfg.Issuer != "" && claims.Issuer != "" && claims.Issuer != s.cfg.Issuer {
|
||||||
|
return nil, errors.New("invalid token issuer")
|
||||||
|
}
|
||||||
|
|
||||||
|
return claims, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) generateToken(username, tokenType string, expiry time.Duration) (string, error) {
|
||||||
|
claims := Claims{
|
||||||
|
Username: username,
|
||||||
|
TokenType: tokenType,
|
||||||
|
RegisteredClaims: jwt.RegisteredClaims{
|
||||||
|
Issuer: s.cfg.Issuer,
|
||||||
|
ExpiresAt: jwt.NewNumericDate(time.Now().Add(expiry)),
|
||||||
|
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||||
|
return token.SignedString(s.secret)
|
||||||
|
}
|
||||||
|
|
||||||
|
func bearerToken(header string) (string, error) {
|
||||||
|
if header == "" {
|
||||||
|
return "", errors.New("missing Auth-Token header")
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(header, "Bearer ") {
|
||||||
|
return "", errors.New("invalid Authorization header format")
|
||||||
|
}
|
||||||
|
|
||||||
|
token := strings.TrimSpace(strings.TrimPrefix(header, "Bearer "))
|
||||||
|
if token == "" {
|
||||||
|
return "", errors.New("empty bearer token")
|
||||||
|
}
|
||||||
|
return token, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ClaimsFromCtx(c fiber.Ctx) (*Claims, bool) {
|
||||||
|
val := c.Locals("authClaims")
|
||||||
|
if val == nil {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
claims, ok := val.(*Claims)
|
||||||
|
return claims, ok
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,89 @@
|
||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ServerConfig struct {
|
||||||
|
AppName string `json:"app_name"`
|
||||||
|
ReadTimeoutSeconds int `json:"read_timeout_seconds"`
|
||||||
|
WriteTimeoutSeconds int `json:"write_timeout_seconds"`
|
||||||
|
IdleTimeoutSeconds int `json:"idle_timeout_seconds"`
|
||||||
|
DisableStartupMessage bool `json:"disable_startup_message"`
|
||||||
|
Auth AuthConfig `json:"auth"`
|
||||||
|
Mail MailConfig `json:"mail"`
|
||||||
|
RolesConfigPath string `json:"roles_config_path"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type AuthConfig struct {
|
||||||
|
Secret string `json:"secret"`
|
||||||
|
Issuer string `json:"issuer"`
|
||||||
|
AccessTokenExpiryMinutes int `json:"access_token_expiry_minutes"`
|
||||||
|
RefreshTokenExpiryMinutes int `json:"refresh_token_expiry_minutes"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type MailConfig struct {
|
||||||
|
Mode string `json:"mode"`
|
||||||
|
From string `json:"from"`
|
||||||
|
DebugDir string `json:"debug_dir"`
|
||||||
|
TemplatesDir string `json:"templates_dir"`
|
||||||
|
FrontendBaseURL string `json:"frontend_base_url"`
|
||||||
|
ResetPasswordPath string `json:"reset_password_path"`
|
||||||
|
SMTP SMTPMailConfig `json:"smtp"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type SMTPMailConfig struct {
|
||||||
|
Host string `json:"host"`
|
||||||
|
Port int `json:"port"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func LoadConfig(path string) (ServerConfig, error) {
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return ServerConfig{}, fmt.Errorf("read config: %w", err)
|
||||||
|
}
|
||||||
|
var cfg ServerConfig
|
||||||
|
if err := json.Unmarshal(data, &cfg); err != nil {
|
||||||
|
return ServerConfig{}, fmt.Errorf("parse config: %w", err)
|
||||||
|
}
|
||||||
|
if cfg.Auth.Secret == "" {
|
||||||
|
return ServerConfig{}, fmt.Errorf("auth.secret must be set")
|
||||||
|
}
|
||||||
|
if cfg.Auth.AccessTokenExpiryMinutes <= 0 {
|
||||||
|
return ServerConfig{}, fmt.Errorf("auth.access_token_expiry_minutes must be greater than zero")
|
||||||
|
}
|
||||||
|
if cfg.Auth.RefreshTokenExpiryMinutes <= 0 {
|
||||||
|
return ServerConfig{}, fmt.Errorf("auth.refresh_token_expiry_minutes must be greater than zero")
|
||||||
|
}
|
||||||
|
if cfg.Mail.Mode == "" {
|
||||||
|
cfg.Mail.Mode = "file"
|
||||||
|
}
|
||||||
|
if cfg.Mail.TemplatesDir == "" {
|
||||||
|
cfg.Mail.TemplatesDir = "internal/http/templates"
|
||||||
|
}
|
||||||
|
if cfg.Mail.ResetPasswordPath == "" {
|
||||||
|
cfg.Mail.ResetPasswordPath = "/#reset-password"
|
||||||
|
}
|
||||||
|
if cfg.Mail.Mode != "smtp" && cfg.Mail.Mode != "file" {
|
||||||
|
return ServerConfig{}, fmt.Errorf("mail.mode must be either smtp or file")
|
||||||
|
}
|
||||||
|
if cfg.Mail.From == "" {
|
||||||
|
return ServerConfig{}, fmt.Errorf("mail.from must be set")
|
||||||
|
}
|
||||||
|
if cfg.Mail.Mode == "smtp" {
|
||||||
|
if cfg.Mail.SMTP.Host == "" {
|
||||||
|
return ServerConfig{}, fmt.Errorf("mail.smtp.host must be set when mail.mode=smtp")
|
||||||
|
}
|
||||||
|
if cfg.Mail.SMTP.Port <= 0 {
|
||||||
|
return ServerConfig{}, fmt.Errorf("mail.smtp.port must be greater than zero when mail.mode=smtp")
|
||||||
|
}
|
||||||
|
} else if cfg.Mail.DebugDir == "" {
|
||||||
|
cfg.Mail.DebugDir = "data/mail-debug"
|
||||||
|
}
|
||||||
|
|
||||||
|
return cfg, nil
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,64 @@
|
||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"server/internal/models"
|
||||||
|
|
||||||
|
"gorm.io/driver/postgres"
|
||||||
|
"gorm.io/driver/sqlite"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
Driver string
|
||||||
|
DSN string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Init opens the configured database connection and runs schema migrations.
|
||||||
|
func Init(cfg Config) (*gorm.DB, error) {
|
||||||
|
switch cfg.Driver {
|
||||||
|
case "sqlite":
|
||||||
|
if err := ensureSQLiteDir(cfg.DSN); err != nil {
|
||||||
|
return nil, fmt.Errorf("prepare sqlite path: %w", err)
|
||||||
|
}
|
||||||
|
db, err := gorm.Open(sqlite.Open(cfg.DSN), &gorm.Config{})
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("open sqlite: %w", err)
|
||||||
|
}
|
||||||
|
if err := db.AutoMigrate(&models.User{}, &models.UserDetails{}, &models.UserPreferences{}, &models.Session{}, &models.PasswordResetToken{}); err != nil {
|
||||||
|
return nil, fmt.Errorf("migrate user: %w", err)
|
||||||
|
}
|
||||||
|
return db, nil
|
||||||
|
case "postgres":
|
||||||
|
db, err := gorm.Open(postgres.Open(cfg.DSN), &gorm.Config{})
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("open postgres: %w", err)
|
||||||
|
}
|
||||||
|
if err := db.AutoMigrate(&models.User{}, &models.UserDetails{}, &models.UserPreferences{}, &models.Session{}, &models.PasswordResetToken{}); err != nil {
|
||||||
|
return nil, fmt.Errorf("migrate user: %w", err)
|
||||||
|
}
|
||||||
|
return db, nil
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("unsupported driver %q", cfg.Driver)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func ensureSQLiteDir(dsn string) error {
|
||||||
|
pathSpec := dsn
|
||||||
|
if idx := strings.Index(pathSpec, "?"); idx >= 0 {
|
||||||
|
pathSpec = pathSpec[:idx]
|
||||||
|
}
|
||||||
|
pathSpec = strings.TrimPrefix(pathSpec, "file:")
|
||||||
|
if pathSpec == "" || strings.Contains(pathSpec, ":memory:") {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
dir := filepath.Dir(pathSpec)
|
||||||
|
if dir == "." || dir == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return os.MkdirAll(dir, 0o755)
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,65 @@
|
||||||
|
package controllers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gofiber/fiber/v3"
|
||||||
|
|
||||||
|
"server/internal/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
type AdminController struct{}
|
||||||
|
|
||||||
|
func NewAdminController() *AdminController {
|
||||||
|
return &AdminController{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Typescript: interface
|
||||||
|
type ListUsersRequest struct {
|
||||||
|
Page int `json:"page" validate:"omitempty,min=1"`
|
||||||
|
PageSize int `json:"pageSize" validate:"omitempty,min=1,max=100"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListUsers returns a paginated list of users (requires admin permissions).
|
||||||
|
func (ac *AdminController) ListUsers(c fiber.Ctx) error {
|
||||||
|
var req ListUsersRequest
|
||||||
|
if err := c.Bind().Body(&req); err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusBadRequest, "invalid payload")
|
||||||
|
}
|
||||||
|
if err := validateStruct(&req); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if req.Page <= 0 {
|
||||||
|
req.Page = 1
|
||||||
|
}
|
||||||
|
if req.PageSize <= 0 || req.PageSize > 100 {
|
||||||
|
req.PageSize = 20
|
||||||
|
}
|
||||||
|
|
||||||
|
db, err := dbFromCtx(c)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var list []models.User
|
||||||
|
offset := (req.Page - 1) * req.PageSize
|
||||||
|
if err := db.Preload("Details").Preload("Preferences").
|
||||||
|
Limit(req.PageSize).
|
||||||
|
Offset(offset).
|
||||||
|
Find(&list).Error; err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "failed to load users")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Map to short representation
|
||||||
|
short := make([]models.UserShort, 0, len(list))
|
||||||
|
for i := range list {
|
||||||
|
short = append(short, models.ToUserShort(&list[i]))
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.JSON(fiber.Map{
|
||||||
|
"data": fiber.Map{
|
||||||
|
"page": req.Page,
|
||||||
|
"pageSize": req.PageSize,
|
||||||
|
"items": short,
|
||||||
|
},
|
||||||
|
"error": nil,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,430 @@
|
||||||
|
package controllers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v3"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
"server/internal/auth"
|
||||||
|
"server/internal/mail"
|
||||||
|
"server/internal/models"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
type AuthController struct {
|
||||||
|
authService *auth.Service
|
||||||
|
mailService *mail.Service
|
||||||
|
}
|
||||||
|
|
||||||
|
// Typescript: interface
|
||||||
|
type SimpleResponse struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewAuthController(authService *auth.Service, mailService *mail.Service) *AuthController {
|
||||||
|
return &AuthController{
|
||||||
|
authService: authService,
|
||||||
|
mailService: mailService,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Typescript: interface
|
||||||
|
type LoginRequest struct {
|
||||||
|
Username string `json:"username" validate:"required,email"`
|
||||||
|
Password string `json:"password" validate:"required,min=8,max=128"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Typescript: interface
|
||||||
|
type RefreshRequest struct {
|
||||||
|
RefreshToken string `json:"refresh_token"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Typescript: interface
|
||||||
|
type ForgotPasswordRequest struct {
|
||||||
|
Email string `json:"email" validate:"required,email"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Typescript: interface
|
||||||
|
type ResetPasswordRequest struct {
|
||||||
|
Token string `json:"token" validate:"required,min=20,max=255"`
|
||||||
|
Password string `json:"password" validate:"required,min=8,max=128"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Login authenticates a user and issues an access/refresh token pair.
|
||||||
|
func (ac *AuthController) Login(c fiber.Ctx) error {
|
||||||
|
var req LoginRequest
|
||||||
|
if err := c.Bind().Body(&req); err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusBadRequest, "invalid payload")
|
||||||
|
}
|
||||||
|
if err := validateStruct(&req); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
db, err := dbFromCtx(c)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var user models.User
|
||||||
|
if err := db.Where("email = ?", req.Username).First(&user).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return fiber.NewError(fiber.StatusUnauthorized, "invalid credentials")
|
||||||
|
}
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "failed to fetch user")
|
||||||
|
}
|
||||||
|
match, err := auth.VerifyPassword(user.Password, req.Password)
|
||||||
|
if err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "failed to verify credentials")
|
||||||
|
}
|
||||||
|
if !match {
|
||||||
|
return fiber.NewError(fiber.StatusUnauthorized, "invalid credentials")
|
||||||
|
}
|
||||||
|
|
||||||
|
tokens, err := ac.authService.GenerateTokenPair(user.Email)
|
||||||
|
if err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "failed to issue token")
|
||||||
|
}
|
||||||
|
|
||||||
|
userID := user.ID
|
||||||
|
now := time.Now().UTC()
|
||||||
|
if err := db.Where("expires_at < ?", now).Delete(&models.Session{}).Error; err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "failed to purge expired sessions")
|
||||||
|
}
|
||||||
|
|
||||||
|
session := models.Session{
|
||||||
|
UserID: &userID,
|
||||||
|
Username: user.Email,
|
||||||
|
AccessTokenHash: hashToken(tokens.AccessToken),
|
||||||
|
RefreshTokenHash: hashToken(tokens.RefreshToken),
|
||||||
|
ExpiresAt: now.Add(ac.authService.RefreshExpiry()),
|
||||||
|
IPAddress: c.IP(),
|
||||||
|
UserAgent: c.Get("User-Agent"),
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := db.Create(&session).Error; err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "failed to record session")
|
||||||
|
}
|
||||||
|
|
||||||
|
//c.Set("Auth-Token", tokens.AccessToken)
|
||||||
|
c.Response().Header.Set("Auth-Token", tokens.AccessToken)
|
||||||
|
|
||||||
|
return c.JSON(success(tokens))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refresh renews an access/refresh token pair using a valid refresh token.
|
||||||
|
func (ac *AuthController) Refresh(c fiber.Ctx) error {
|
||||||
|
var req RefreshRequest
|
||||||
|
if err := c.Bind().Body(&req); err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusBadRequest, "invalid payload")
|
||||||
|
}
|
||||||
|
if req.RefreshToken == "" {
|
||||||
|
return fiber.NewError(fiber.StatusBadRequest, "refresh_token is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
tokens, err := ac.authService.Refresh(req.RefreshToken)
|
||||||
|
if err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusUnauthorized, err.Error())
|
||||||
|
}
|
||||||
|
return c.JSON(success(tokens))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Me returns the authenticated user's profile (short format).
|
||||||
|
func (ac *AuthController) Me(c fiber.Ctx) error {
|
||||||
|
claims, ok := auth.ClaimsFromCtx(c)
|
||||||
|
if !ok {
|
||||||
|
return fiber.NewError(fiber.StatusUnauthorized, "missing claims")
|
||||||
|
}
|
||||||
|
|
||||||
|
db, err := dbFromCtx(c)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var user models.User
|
||||||
|
if err := db.Preload("Details").Preload("Preferences").Where("email = ?", claims.Username).First(&user).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return fiber.NewError(fiber.StatusNotFound, "user not found")
|
||||||
|
}
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "failed to load user")
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.JSON(success(models.ToUserShort(&user)))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Register creates a new user with optional roles/types/preferences.
|
||||||
|
func (ac *AuthController) Register(c fiber.Ctx) error {
|
||||||
|
var req models.UserCreateInput
|
||||||
|
if err := c.Bind().Body(&req); err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusBadRequest, "invalid payload")
|
||||||
|
}
|
||||||
|
if err := validateStruct(&req); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
db, err := dbFromCtx(c)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var existing models.User
|
||||||
|
if err := db.Where("email = ?", req.Email).First(&existing).Error; err == nil {
|
||||||
|
return fiber.NewError(fiber.StatusConflict, "user already exists")
|
||||||
|
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "failed to check user")
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now().UTC()
|
||||||
|
hashedPassword, err := auth.HashPassword(req.Password)
|
||||||
|
if err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "failed to secure password")
|
||||||
|
}
|
||||||
|
user := models.User{
|
||||||
|
Email: req.Email,
|
||||||
|
Name: req.Name,
|
||||||
|
Password: hashedPassword,
|
||||||
|
Roles: func() models.UserRoles {
|
||||||
|
if len(req.Roles) == 0 {
|
||||||
|
return models.UserRoles{"user"}
|
||||||
|
}
|
||||||
|
return req.Roles
|
||||||
|
}(),
|
||||||
|
Status: func() models.UserStatus {
|
||||||
|
if req.Status == "" {
|
||||||
|
return models.UserStatusPending
|
||||||
|
}
|
||||||
|
return req.Status
|
||||||
|
}(),
|
||||||
|
Types: func() models.UserTypes {
|
||||||
|
if len(req.Types) == 0 {
|
||||||
|
return models.UserTypes{"internal"}
|
||||||
|
}
|
||||||
|
return req.Types
|
||||||
|
}(),
|
||||||
|
Avatar: req.Avatar,
|
||||||
|
UUID: uuid.NewString(),
|
||||||
|
Details: toUserDetails(req.Details),
|
||||||
|
Preferences: func() *models.UserPreferences {
|
||||||
|
if req.Preferences == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &models.UserPreferences{
|
||||||
|
UseIdle: req.Preferences.UseIdle,
|
||||||
|
IdleTimeout: req.Preferences.IdleTimeout,
|
||||||
|
UseIdlePassword: req.Preferences.UseIdlePassword,
|
||||||
|
IdlePin: req.Preferences.IdlePin,
|
||||||
|
UseDirectLogin: req.Preferences.UseDirectLogin,
|
||||||
|
UseQuadcodeLogin: req.Preferences.UseQuadcodeLogin,
|
||||||
|
SendNoticesMail: req.Preferences.SendNoticesMail,
|
||||||
|
Language: req.Preferences.Language,
|
||||||
|
}
|
||||||
|
}(),
|
||||||
|
CreatedAt: now,
|
||||||
|
UpdatedAt: now,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := db.Create(&user).Error; err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "failed to create user")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := ac.mailService.Send(c, mail.Message{
|
||||||
|
To: user.Email,
|
||||||
|
Subject: fmt.Sprintf("[%s] Registrazione completata", ac.mailService.AppName()),
|
||||||
|
Template: "registration",
|
||||||
|
TemplateData: mail.TemplateData{
|
||||||
|
AppName: ac.mailService.AppName(),
|
||||||
|
UserName: user.Name,
|
||||||
|
UserEmail: user.Email,
|
||||||
|
},
|
||||||
|
}); err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "failed to send registration email")
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.Status(fiber.StatusCreated).JSON(success(models.ToUserShort(&user)))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ac *AuthController) ForgotPassword(c fiber.Ctx) error {
|
||||||
|
var req ForgotPasswordRequest
|
||||||
|
if err := c.Bind().Body(&req); err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusBadRequest, "invalid payload")
|
||||||
|
}
|
||||||
|
if err := validateStruct(&req); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
db, err := dbFromCtx(c)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var user models.User
|
||||||
|
if err := db.Where("email = ?", req.Email).First(&user).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return c.JSON(success(fiber.Map{"sent": true}))
|
||||||
|
}
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "failed to load user")
|
||||||
|
}
|
||||||
|
|
||||||
|
if user.Status == models.UserStatusDisabled {
|
||||||
|
return c.JSON(success(fiber.Map{"sent": true}))
|
||||||
|
}
|
||||||
|
|
||||||
|
resetToken, err := generateSecureToken()
|
||||||
|
if err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "failed to generate reset token")
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now().UTC()
|
||||||
|
record := models.PasswordResetToken{
|
||||||
|
UserID: user.ID,
|
||||||
|
TokenHash: hashToken(resetToken),
|
||||||
|
ExpiresAt: now.Add(30 * time.Minute),
|
||||||
|
CreatedAt: now,
|
||||||
|
UpdatedAt: now,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
if err := tx.Where("user_id = ? OR expires_at < ? OR used_at IS NOT NULL", user.ID, now).
|
||||||
|
Delete(&models.PasswordResetToken{}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return tx.Create(&record).Error
|
||||||
|
}); err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "failed to store reset token")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := ac.mailService.Send(c, mail.Message{
|
||||||
|
To: user.Email,
|
||||||
|
Subject: fmt.Sprintf("[%s] Recupero password", ac.mailService.AppName()),
|
||||||
|
Template: "password_reset",
|
||||||
|
TemplateData: mail.TemplateData{
|
||||||
|
AppName: ac.mailService.AppName(),
|
||||||
|
UserName: user.Name,
|
||||||
|
UserEmail: user.Email,
|
||||||
|
ResetToken: resetToken,
|
||||||
|
ResetURL: ac.mailService.ResetLink(resetToken),
|
||||||
|
},
|
||||||
|
}); err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "failed to send reset email")
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.JSON(success(SimpleResponse{Message: "password reset email sent"}))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ac *AuthController) ResetPassword(c fiber.Ctx) error {
|
||||||
|
var req ResetPasswordRequest
|
||||||
|
if err := c.Bind().Body(&req); err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusBadRequest, "invalid payload")
|
||||||
|
}
|
||||||
|
if err := validateStruct(&req); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
db, err := dbFromCtx(c)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
hashedPassword, err := auth.HashPassword(req.Password)
|
||||||
|
if err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "failed to secure password")
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now().UTC()
|
||||||
|
tokenHash := hashToken(req.Token)
|
||||||
|
if err := db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
var resetToken models.PasswordResetToken
|
||||||
|
if err := tx.Where("token_hash = ?", tokenHash).First(&resetToken).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return fiber.NewError(fiber.StatusBadRequest, "invalid or expired reset token")
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if resetToken.UsedAt != nil || now.After(resetToken.ExpiresAt) {
|
||||||
|
return fiber.NewError(fiber.StatusBadRequest, "invalid or expired reset token")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tx.Model(&models.User{}).Where("id = ?", resetToken.UserID).Updates(map[string]any{
|
||||||
|
"password": hashedPassword,
|
||||||
|
"updated_at": now,
|
||||||
|
}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := tx.Model(&resetToken).Updates(map[string]any{
|
||||||
|
"used_at": now,
|
||||||
|
"updated_at": now,
|
||||||
|
}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := tx.Where("user_id = ?", resetToken.UserID).Delete(&models.Session{}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := tx.Where("user_id = ? AND id <> ?", resetToken.UserID, resetToken.ID).Delete(&models.PasswordResetToken{}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}); err != nil {
|
||||||
|
var fiberErr *fiber.Error
|
||||||
|
if errors.As(err, &fiberErr) {
|
||||||
|
return fiberErr
|
||||||
|
}
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "failed to reset password")
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.JSON(success(SimpleResponse{Message: "password reset successful"}))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ac *AuthController) ValidToken(c fiber.Ctx) error {
|
||||||
|
raw := strings.TrimSpace(string(c.Body()))
|
||||||
|
if raw == "" {
|
||||||
|
return fiber.NewError(fiber.StatusBadRequest, "token is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Accept both plain text token payload and JSON string payload.
|
||||||
|
token := raw
|
||||||
|
if strings.HasPrefix(raw, "\"") && strings.HasSuffix(raw, "\"") {
|
||||||
|
if err := json.Unmarshal([]byte(raw), &token); err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusBadRequest, "invalid payload")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
token = strings.TrimSpace(token)
|
||||||
|
if token == "" {
|
||||||
|
return fiber.NewError(fiber.StatusBadRequest, "token is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
db, err := dbFromCtx(c)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now().UTC()
|
||||||
|
tokenHash := hashToken(token)
|
||||||
|
var resetToken models.PasswordResetToken
|
||||||
|
if err := db.Where("token_hash = ?", tokenHash).First(&resetToken).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return fiber.NewError(fiber.StatusBadRequest, "invalid or expired reset token")
|
||||||
|
}
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "failed to validate reset token")
|
||||||
|
}
|
||||||
|
|
||||||
|
if resetToken.UsedAt != nil || now.After(resetToken.ExpiresAt) {
|
||||||
|
return fiber.NewError(fiber.StatusBadRequest, "invalid or expired reset token")
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.JSON(success(SimpleResponse{Message: "valid reset token"}))
|
||||||
|
}
|
||||||
|
|
||||||
|
func generateSecureToken() (string, error) {
|
||||||
|
buf := make([]byte, 32)
|
||||||
|
if _, err := rand.Read(buf); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return base64.RawURLEncoding.EncodeToString(buf), nil
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,223 @@
|
||||||
|
package controllers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v3"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
"server/internal/auth"
|
||||||
|
"server/internal/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RoleConfig struct {
|
||||||
|
Roles map[string][]string `json:"roles"`
|
||||||
|
Permissions map[string][]string `json:"permissions"`
|
||||||
|
Endpoints map[string]string `json:"endpoints"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type RoleResolver struct {
|
||||||
|
roleClosure map[string]map[string]struct{}
|
||||||
|
permMap map[string]map[string]struct{}
|
||||||
|
endpointPerm map[string]string
|
||||||
|
}
|
||||||
|
|
||||||
|
func LoadRoleConfig(path string) (*RoleResolver, error) {
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("read role config: %w", err)
|
||||||
|
}
|
||||||
|
var cfg RoleConfig
|
||||||
|
if err := json.Unmarshal(data, &cfg); err != nil {
|
||||||
|
return nil, fmt.Errorf("parse role config: %w", err)
|
||||||
|
}
|
||||||
|
res := &RoleResolver{
|
||||||
|
roleClosure: make(map[string]map[string]struct{}),
|
||||||
|
permMap: make(map[string]map[string]struct{}),
|
||||||
|
endpointPerm: make(map[string]string),
|
||||||
|
}
|
||||||
|
|
||||||
|
for role := range cfg.Roles {
|
||||||
|
res.roleClosure[role] = make(map[string]struct{})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compute role closure (role implies itself).
|
||||||
|
var dfs func(string, map[string]struct{})
|
||||||
|
dfs = func(role string, seen map[string]struct{}) {
|
||||||
|
if _, ok := seen[role]; ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
seen[role] = struct{}{}
|
||||||
|
if implied, ok := cfg.Roles[role]; ok {
|
||||||
|
for _, r := range implied {
|
||||||
|
dfs(r, seen)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for role := range cfg.Roles {
|
||||||
|
set := make(map[string]struct{})
|
||||||
|
set[role] = struct{}{}
|
||||||
|
dfs(role, set)
|
||||||
|
res.roleClosure[role] = set
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build permission map including inherited permissions.
|
||||||
|
for role := range cfg.Roles {
|
||||||
|
res.permMap[role] = make(map[string]struct{})
|
||||||
|
}
|
||||||
|
for role := range cfg.Roles {
|
||||||
|
closure := res.roleClosure[role]
|
||||||
|
for implied := range closure {
|
||||||
|
for _, p := range cfg.Permissions[implied] {
|
||||||
|
res.permMap[role][p] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normalise endpoints to "METHOD /path".
|
||||||
|
for key, perm := range cfg.Endpoints {
|
||||||
|
parts := strings.SplitN(key, " ", 2)
|
||||||
|
if len(parts) != 2 {
|
||||||
|
return nil, fmt.Errorf("invalid endpoint key %q", key)
|
||||||
|
}
|
||||||
|
method := strings.TrimSpace(strings.ToUpper(parts[0]))
|
||||||
|
path := strings.TrimSpace(parts[1])
|
||||||
|
res.endpointPerm[method+" "+path] = perm
|
||||||
|
}
|
||||||
|
|
||||||
|
return res, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *RoleResolver) HasRole(userRoles []string, required string) bool {
|
||||||
|
for _, ur := range userRoles {
|
||||||
|
if closure, ok := r.roleClosure[ur]; ok {
|
||||||
|
if _, present := closure[required]; present {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *RoleResolver) HasPermission(userRoles []string, perm string) bool {
|
||||||
|
for _, ur := range userRoles {
|
||||||
|
if perms, ok := r.permMap[ur]; ok {
|
||||||
|
if _, present := perms[perm]; present {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *RoleResolver) PermissionForEndpoint(method, path string) (string, bool) {
|
||||||
|
key := strings.ToUpper(method) + " " + path
|
||||||
|
perm, ok := r.endpointPerm[key]
|
||||||
|
return perm, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *RoleResolver) RoleDefined(role string) bool {
|
||||||
|
_, ok := r.roleClosure[role]
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// RequireRole ensures the authenticated user has the specified role (with inheritance).
|
||||||
|
func RequireRole(resolver *RoleResolver, role string) fiber.Handler {
|
||||||
|
return func(c fiber.Ctx) error {
|
||||||
|
claims, ok := auth.ClaimsFromCtx(c)
|
||||||
|
if !ok {
|
||||||
|
return fiber.NewError(fiber.StatusUnauthorized, "missing claims")
|
||||||
|
}
|
||||||
|
|
||||||
|
db, err := dbFromCtx(c)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var user models.User
|
||||||
|
if err := db.Select("roles").Where("email = ?", claims.Username).First(&user).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return fiber.NewError(fiber.StatusUnauthorized, "user not found")
|
||||||
|
}
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "failed to load user roles")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !resolver.HasRole(user.Roles, role) {
|
||||||
|
return fiber.NewError(fiber.StatusForbidden, "insufficient permissions")
|
||||||
|
}
|
||||||
|
return c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RequirePermission ensures the authenticated user has the given permission.
|
||||||
|
func RequirePermission(resolver *RoleResolver, perm string) fiber.Handler {
|
||||||
|
return func(c fiber.Ctx) error {
|
||||||
|
claims, ok := auth.ClaimsFromCtx(c)
|
||||||
|
if !ok {
|
||||||
|
return fiber.NewError(fiber.StatusUnauthorized, "missing claims")
|
||||||
|
}
|
||||||
|
|
||||||
|
db, err := dbFromCtx(c)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var user models.User
|
||||||
|
if err := db.Select("roles").Where("email = ?", claims.Username).First(&user).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return fiber.NewError(fiber.StatusUnauthorized, "user not found")
|
||||||
|
}
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "failed to load user roles")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !resolver.HasPermission(user.Roles, perm) {
|
||||||
|
return fiber.NewError(fiber.StatusForbidden, "insufficient permissions")
|
||||||
|
}
|
||||||
|
return c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RequireEndpointPermission enforces permission mapping defined in role config.
|
||||||
|
// If the endpoint is not configured, or mapped to "*", it allows the request.
|
||||||
|
func RequireEndpointPermission(resolver *RoleResolver, authService *auth.Service) fiber.Handler {
|
||||||
|
return func(c fiber.Ctx) error {
|
||||||
|
perm, ok := resolver.PermissionForEndpoint(c.Method(), c.Path())
|
||||||
|
if !ok || perm == "*" {
|
||||||
|
return c.Next()
|
||||||
|
}
|
||||||
|
|
||||||
|
tokenString := c.Get("Auth-Token")
|
||||||
|
if tokenString == "" {
|
||||||
|
return fiber.NewError(fiber.StatusUnauthorized, "missing token header")
|
||||||
|
}
|
||||||
|
|
||||||
|
claims, err := authService.ValidateAccessToken(tokenString)
|
||||||
|
if err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusUnauthorized, err.Error())
|
||||||
|
}
|
||||||
|
c.Locals("authClaims", claims)
|
||||||
|
|
||||||
|
db, err := dbFromCtx(c)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var user models.User
|
||||||
|
if err := db.Select("roles").Where("email = ?", claims.Username).First(&user).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return fiber.NewError(fiber.StatusUnauthorized, "user not found")
|
||||||
|
}
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "failed to load user roles")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !resolver.HasPermission(user.Roles, perm) {
|
||||||
|
return fiber.NewError(fiber.StatusForbidden, "insufficient permissions")
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,34 @@
|
||||||
|
package controllers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gofiber/fiber/v3"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
"server/internal/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
// dbFromCtx extracts *gorm.DB from Fiber context.
|
||||||
|
func dbFromCtx(c fiber.Ctx) (*gorm.DB, error) {
|
||||||
|
dbVal := c.Locals("db")
|
||||||
|
db, ok := dbVal.(*gorm.DB)
|
||||||
|
if !ok || db == nil {
|
||||||
|
return nil, fiber.NewError(fiber.StatusInternalServerError, "database unavailable")
|
||||||
|
}
|
||||||
|
return db, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func toUserDetails(d *models.UserDetailsShort) *models.UserDetails {
|
||||||
|
if d == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &models.UserDetails{
|
||||||
|
Title: d.Title,
|
||||||
|
FirstName: d.FirstName,
|
||||||
|
LastName: d.LastName,
|
||||||
|
Address: d.Address,
|
||||||
|
City: d.City,
|
||||||
|
ZipCode: d.ZipCode,
|
||||||
|
Country: d.Country,
|
||||||
|
Phone: d.Phone,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
package controllers
|
||||||
|
|
||||||
|
import "github.com/gofiber/fiber/v3"
|
||||||
|
|
||||||
|
// success wraps a payload in the standard API envelope.
|
||||||
|
func success(data any) fiber.Map {
|
||||||
|
return fiber.Map{
|
||||||
|
"data": data,
|
||||||
|
"error": nil,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
package controllers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
)
|
||||||
|
|
||||||
|
func hashToken(token string) string {
|
||||||
|
sum := sha256.Sum256([]byte(token))
|
||||||
|
return hex.EncodeToString(sum[:])
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,28 @@
|
||||||
|
package controllers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/go-playground/validator/v10"
|
||||||
|
"github.com/gofiber/fiber/v3"
|
||||||
|
)
|
||||||
|
|
||||||
|
var validate = validator.New(validator.WithRequiredStructEnabled())
|
||||||
|
|
||||||
|
// validateStruct runs tag-based validation and returns a Fiber 400 error on failure.
|
||||||
|
func validateStruct(payload any) error {
|
||||||
|
if err := validate.Struct(payload); err != nil {
|
||||||
|
if _, ok := err.(*validator.InvalidValidationError); ok {
|
||||||
|
return fiber.NewError(fiber.StatusBadRequest, "invalid payload")
|
||||||
|
}
|
||||||
|
if verrs, ok := err.(validator.ValidationErrors); ok && len(verrs) > 0 {
|
||||||
|
fe := verrs[0]
|
||||||
|
field := strings.ToLower(fe.Field())
|
||||||
|
msg := fmt.Sprintf("%s validation failed (%s)", field, fe.ActualTag())
|
||||||
|
return fiber.NewError(fiber.StatusBadRequest, msg)
|
||||||
|
}
|
||||||
|
return fiber.NewError(fiber.StatusBadRequest, "validation failed")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,14 @@
|
||||||
|
package routes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"server/internal/http/controllers"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v3"
|
||||||
|
)
|
||||||
|
|
||||||
|
func registerAdminRoutes(app *fiber.App) {
|
||||||
|
adminController := controllers.NewAdminController()
|
||||||
|
|
||||||
|
// Typescript: TSEndpoint= path=/admin/users; name=listUsers; method=POST; request=controllers.ListUsersRequest; response=models.[]UserShort
|
||||||
|
app.Post("/admin/users", adminController.ListUsers)
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,42 @@
|
||||||
|
package routes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"server/internal/auth"
|
||||||
|
"server/internal/http/controllers"
|
||||||
|
"server/internal/mail"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v3"
|
||||||
|
"github.com/gofiber/fiber/v3/middleware/limiter"
|
||||||
|
)
|
||||||
|
|
||||||
|
func registerAuthRoutes(app *fiber.App, authService *auth.Service, mailService *mail.Service) {
|
||||||
|
authController := controllers.NewAuthController(authService, mailService)
|
||||||
|
authRateLimiter := limiter.New(limiter.Config{
|
||||||
|
Max: 10,
|
||||||
|
Expiration: time.Minute,
|
||||||
|
LimiterMiddleware: limiter.SlidingWindow{},
|
||||||
|
})
|
||||||
|
|
||||||
|
// Typescript: TSEndpoint= path=/auth/login; name=login; method=POST; request=controllers.LoginRequest; response=auth.TokenPair
|
||||||
|
app.Post("/auth/login", authRateLimiter, authController.Login)
|
||||||
|
|
||||||
|
// Typescript: TSEndpoint= path=/auth/refresh; name=refresh; method=POST; request=controllers.RefreshRequest; response=auth.TokenPair
|
||||||
|
app.Post("/auth/refresh", authService.Middleware(), authController.Refresh)
|
||||||
|
|
||||||
|
// Typescript: TSEndpoint= path=/auth/me; name=me; method=GET; response=models.UserShort
|
||||||
|
app.Get("/auth/me", authService.Middleware(), authController.Me)
|
||||||
|
|
||||||
|
// Typescript: TSEndpoint= path=/auth/register; name=register; method=POST; request=models.UserCreateInput; response=models.UserShort
|
||||||
|
app.Post("/auth/register", authRateLimiter, authController.Register)
|
||||||
|
|
||||||
|
// Typescript: TSEndpoint= path=/auth/password/forgot; name=forgotPassword; method=POST; request=controllers.ForgotPasswordRequest; response=controllers.SimpleResponse
|
||||||
|
app.Post("/auth/password/forgot", authRateLimiter, authController.ForgotPassword)
|
||||||
|
|
||||||
|
// Typescript: TSEndpoint= path=/auth/password/reset; name=resetPassword; method=POST; request=controllers.ResetPasswordRequest; response=controllers.SimpleResponse
|
||||||
|
app.Post("/auth/password/reset", authRateLimiter, authController.ResetPassword)
|
||||||
|
|
||||||
|
// Typescript: TSEndpoint= path=/auth/password/valid; name=validToken; method=POST; request=string; response=controllers.SimpleResponse
|
||||||
|
app.Post("/auth/password/valid", authRateLimiter, authController.ValidToken)
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,25 @@
|
||||||
|
package routes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"server/internal/auth"
|
||||||
|
"server/internal/mail"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v3"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Typescript: interface
|
||||||
|
type FormRequest struct {
|
||||||
|
Req string `json:"req"`
|
||||||
|
Count int `json:"count"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Typescript: interface
|
||||||
|
type FormResponse struct {
|
||||||
|
Test string `json:"test"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func Register(app *fiber.App, authService *auth.Service, mailService *mail.Service) {
|
||||||
|
registerSystemRoutes(app)
|
||||||
|
registerAuthRoutes(app, authService, mailService)
|
||||||
|
registerAdminRoutes(app)
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,94 @@
|
||||||
|
package routes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"server/internal/tsgenerator"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v3"
|
||||||
|
"github.com/gofiber/fiber/v3/middleware/static"
|
||||||
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||||
|
)
|
||||||
|
|
||||||
|
const spaDistPath = "internal/http/static/spa"
|
||||||
|
|
||||||
|
// Typescript: interface
|
||||||
|
type MailDebugItem struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Content string `json:"content"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// healthHandler returns a simple application health status.
|
||||||
|
func healthHandler(c fiber.Ctx) error {
|
||||||
|
return c.JSON(fiber.Map{
|
||||||
|
"data": fiber.Map{"status": "ok", "ts": time.Now().UTC()},
|
||||||
|
"error": nil,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func registerSystemRoutes(app *fiber.App) {
|
||||||
|
// Typescript: TSEndpoint= path=/health; name=health; method=GET; response=string
|
||||||
|
app.Get("/health", healthHandler)
|
||||||
|
|
||||||
|
// Typescript: TSEndpoint= path=/metrics; name=metrics; method=GET; response=string
|
||||||
|
app.Get("/metrics", promhttp.Handler())
|
||||||
|
|
||||||
|
app.Get("/tsgenerate", func(c fiber.Ctx) error {
|
||||||
|
ts, err := tsgenerator.TsGenerate()
|
||||||
|
if err != nil {
|
||||||
|
return c.Status(fiber.StatusInternalServerError).SendString(err.Error())
|
||||||
|
}
|
||||||
|
return c.SendString(ts)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Typescript: TSEndpoint= path=/maildebug; name=mailDebug; method=GET; response=routes.[]MailDebugItem
|
||||||
|
app.Get("/maildebug", func(c fiber.Ctx) error {
|
||||||
|
entries, err := os.ReadDir("data/mail-debug")
|
||||||
|
if err != nil {
|
||||||
|
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||||
|
"data": nil,
|
||||||
|
"error": fmt.Sprintf("failed to read mail-debug directory: %v", err),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
items := make([]MailDebugItem, 0, len(entries))
|
||||||
|
for _, entry := range entries {
|
||||||
|
if entry.IsDir() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
name := entry.Name()
|
||||||
|
path := filepath.Join("data/mail-debug", name)
|
||||||
|
b, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||||
|
"data": nil,
|
||||||
|
"error": fmt.Sprintf("failed to read mail file %s: %v", name, err),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
items = append(items, MailDebugItem{
|
||||||
|
Name: name,
|
||||||
|
Content: string(b),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
sort.Slice(items, func(i, j int) bool {
|
||||||
|
return items[i].Name < items[j].Name
|
||||||
|
})
|
||||||
|
|
||||||
|
return c.JSON(fiber.Map{
|
||||||
|
"data": items,
|
||||||
|
"error": nil,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
app.Get("/", func(c fiber.Ctx) error {
|
||||||
|
return c.SendFile(filepath.Join(spaDistPath, "index.html"))
|
||||||
|
})
|
||||||
|
app.Use("/", static.New(spaDistPath))
|
||||||
|
}
|
||||||
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1 @@
|
||||||
|
.api-tester-page[data-v-a5a44d8d]{background:radial-gradient(circle at 15% 20%,#fcecc9 0%,transparent 32%),radial-gradient(circle at 85% 10%,#d8f4f8 0%,transparent 35%),linear-gradient(145deg,#f7f3ec,#eef8f9);min-height:100vh;padding:28px 16px 36px}.page-shell[data-v-a5a44d8d]{max-width:1240px;margin:0 auto}.page-header[data-v-a5a44d8d]{margin-bottom:20px}.eyebrow[data-v-a5a44d8d]{margin:0;letter-spacing:.2em;text-transform:uppercase;color:#395f76;font-weight:700;font-size:11px}.page-header h1[data-v-a5a44d8d]{margin:6px 0;font-family:Space Grotesk,sans-serif;font-size:clamp(1.6rem,2.8vw,2.3rem)}.subtitle[data-v-a5a44d8d]{margin:0;color:#50626f;max-width:760px}.cards-grid[data-v-a5a44d8d]{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:16px}.endpoint-card[data-v-a5a44d8d]{border-radius:14px;-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);background:#ffffffbf}.card-head[data-v-a5a44d8d]{display:flex;flex-direction:column;gap:8px}.head-main[data-v-a5a44d8d]{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.head-main code[data-v-a5a44d8d]{background:#f1f4f7;border:1px solid #dce5eb;border-radius:8px;padding:2px 8px}.card-body[data-v-a5a44d8d]{min-height:160px}.no-fields[data-v-a5a44d8d]{padding:8px;color:#60717f}.field-grid[data-v-a5a44d8d]{display:grid;gap:10px}.card-actions[data-v-a5a44d8d]{padding:12px 16px 16px}.result-card[data-v-a5a44d8d]{background:#0f1a24;color:#e7edf3}.result-header[data-v-a5a44d8d]{background:linear-gradient(90deg,#152434,#244661)}.result-body[data-v-a5a44d8d]{display:grid;grid-template-columns:1fr;gap:16px;max-height:calc(100vh - 210px);overflow-y:auto}.result-block[data-v-a5a44d8d]{background:#162432;border:1px solid #2c465f;border-radius:12px;padding:12px}.result-block h3[data-v-a5a44d8d]{margin:0 0 8px;font-size:13px;text-transform:uppercase;letter-spacing:.08em;color:#9bc2de}.result-block pre[data-v-a5a44d8d]{margin:0;white-space:pre-wrap;word-break:break-word;font-size:12px}@media(max-width:640px){.api-tester-page[data-v-a5a44d8d]{padding-top:18px}.cards-grid[data-v-a5a44d8d]{grid-template-columns:1fr}}
|
||||||
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1 @@
|
||||||
|
import{Q as o}from"./QBtn-AYMizH8c.js";import{a as s,o as l,k as r,h as t,f as n}from"./index-QUdrNkKl.js";import"./render-B4qP-w0Q.js";const a={class:"fullscreen bg-blue text-white text-center q-pa-md flex flex-center"},f=s({__name:"ErrorNotFound",setup(i){return(c,e)=>(l(),r("div",a,[t("div",null,[e[0]||(e[0]=t("div",{style:{"font-size":"30vh"}},"404",-1)),e[1]||(e[1]=t("div",{class:"text-h2",style:{opacity:"0.4"}},"Oops. Nothing here...",-1)),n(o,{class:"q-mt-xl",color:"white","text-color":"blue",unelevated:"",to:"/",label:"Go Home","no-caps":""})])]))}});export{f as default};
|
||||||
|
|
@ -0,0 +1 @@
|
||||||
|
.my-card[data-v-ab3d870b]{width:100%;max-width:250px}
|
||||||
|
|
@ -0,0 +1 @@
|
||||||
|
import{Q as e}from"./QPage-gf8hzrox.js";import{a as o,o as t,e as a}from"./index-QUdrNkKl.js";import"./render-B4qP-w0Q.js";const _=o({__name:"IndexPage",setup(r){return(s,n)=>(t(),a(e,{class:"row items-center justify-evenly"}))}});export{_ as default};
|
||||||
File diff suppressed because one or more lines are too long
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -0,0 +1 @@
|
||||||
|
.mail-debug-page[data-v-1b5b3a76]{min-height:100vh;background:radial-gradient(circle at 12% 10%,#fde9d5 0%,transparent 30%),radial-gradient(circle at 86% 18%,#d9f5ee 0%,transparent 35%),linear-gradient(140deg,#f8f4ed,#edf8f7);padding:24px 16px 32px}.mail-debug-shell[data-v-1b5b3a76]{max-width:1300px;margin:0 auto}.mail-debug-header[data-v-1b5b3a76]{margin-bottom:16px}.eyebrow[data-v-1b5b3a76]{margin:0;letter-spacing:.18em;text-transform:uppercase;color:#375266;font-size:11px;font-weight:700}.mail-debug-header h1[data-v-1b5b3a76]{margin:4px 0;font-family:Space Grotesk,sans-serif;font-size:clamp(1.6rem,2.8vw,2.3rem)}.subtitle[data-v-1b5b3a76]{margin:0;color:#4f6676}.mail-debug-card[data-v-1b5b3a76]{border-radius:14px;background:#fffc}.controls[data-v-1b5b3a76]{display:flex;gap:12px;align-items:center;flex-wrap:wrap}.mail-select[data-v-1b5b3a76]{min-width:280px;flex:1}.preview-grid[data-v-1b5b3a76]{display:grid;grid-template-columns:290px 1fr;gap:16px}.meta-column[data-v-1b5b3a76]{background:#f2f7fb;border:1px solid #d7e5f1;border-radius:12px;padding:14px}.meta-label[data-v-1b5b3a76]{margin:0;text-transform:uppercase;letter-spacing:.1em;font-size:11px;color:#5d7586}.meta-column h2[data-v-1b5b3a76]{margin:8px 0 16px;font-size:1.2rem;word-break:break-word}.meta-line[data-v-1b5b3a76]{margin:0 0 10px;color:#4a6171;word-break:break-word}.preview-column[data-v-1b5b3a76]{min-width:0}.preview-frame[data-v-1b5b3a76]{width:100%;min-height:68vh;border:1px solid #d8e2ea;border-radius:12px;background:#fff}.empty-state[data-v-1b5b3a76],.error-box[data-v-1b5b3a76]{border-radius:10px;padding:12px}.empty-state[data-v-1b5b3a76]{background:#edf3f8;color:#5b7080}.error-box[data-v-1b5b3a76]{background:#fdeceb;color:#9f2b2b}@media(max-width:860px){.preview-grid[data-v-1b5b3a76]{grid-template-columns:1fr}.preview-frame[data-v-1b5b3a76]{min-height:55vh}}
|
||||||
|
|
@ -0,0 +1 @@
|
||||||
|
import{Q as k}from"./QBtn-AYMizH8c.js";import{Q as A}from"./QSelect-QjDUAbKc.js";import{Q as E,a as x}from"./QCard-D_vcm7k9.js";import{Q as H,e as Z}from"./api-rhge6pbe.js";import{Q as F}from"./QPage-gf8hzrox.js";import{M as P,a3 as q,a as j,x as I,o as r,e as R,w as f,h as t,g as v,f as n,k as m,t as g,Z as z,q as b,p as y}from"./index-QUdrNkKl.js";import{_ as K}from"./_plugin-vue_export-helper-DlAUqK2U.js";import"./render-B4qP-w0Q.js";import"./use-key-composition-TTwP9QMZ.js";import"./use-dark-BRt0_t6X.js";import"./QItem-F5bzVaJB.js";import"./format-GjIIeqP4.js";import"./use-prevent-scroll-eZQDeoK_.js";import"./QDialog-BcbjPBVh.js";import"./use-timeout-Jkrq6Sig.js";function O(){return P(q)}const U={class:"mail-debug-shell"},G={key:0,class:"error-box"},J={key:1,class:"empty-state"},W={key:2,class:"preview-grid"},X={class:"meta-column"},Y={key:0,class:"meta-line"},ee={key:1,class:"meta-line"},ae={class:"preview-column"},le=["srcdoc"],te=j({__name:"MailDebugPage",setup(oe){const M=O(),p=b(!1),o=b([]),s=b(null),u=b(""),Q=y(()=>o.value.map((a,e)=>({label:N(a.name||`Mail ${e+1}`).displayName,value:e}))),i=y(()=>s.value===null?null:o.value[s.value]??null),c=y(()=>i.value?N(i.value.name):{displayName:"",email:null,localDate:null}),$=y(()=>S(i.value?.content??""));function S(a){const e='<base target="_blank" rel="noopener noreferrer">';return/<base\s/i.test(a)?a:/<head[^>]*>/i.test(a)?a.replace(/<head[^>]*>/i,l=>`${l}${e}`):`${e}${a}`}function N(a){const e=a.replace(/\.eml$/i,""),l=e.match(/^(\d{10,20})_(.+)$/);let d=e,_=null;l?.[1]&&l[2]&&(_=l[1],d=l[2]);const w=d.replace(/_at_/gi,"@"),h=w.match(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/),V=(_?C(_):null)??L(e);return{displayName:h?.[0]??w,email:h?h[0]:null,localDate:V}}function C(a){const e=Number(a);if(!Number.isFinite(e))return null;let l=e;a.length>=19?l=Math.floor(e/1e6):a.length>=16?l=Math.floor(e/1e3):a.length<=10&&(l=e*1e3);const d=new Date(l);return Number.isNaN(d.getTime())?null:d.toLocaleString()}function L(a){const e=a.match(/(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z?)/);if(e)return D(e[0]);const l=a.match(/(\d{4}-\d{2}-\d{2}[ _]\d{2}[-:]\d{2}[-:]\d{2})/);return l?D(l[0]):null}function D(a){const e=a.replace(" ","T").replace(/(T\d{2})-(\d{2})-(\d{2})$/,"$1:$2:$3"),l=new Date(e);return Number.isNaN(l.getTime())?a:l.toLocaleString()}async function T(){p.value=!0,u.value="";try{const a=await Z();if(a.error){u.value=a.error,o.value=[],s.value=null;return}o.value=Array.isArray(a.data)?a.data:[],s.value=o.value.length>0?0:null}catch(a){u.value=a instanceof Error?a.message:String(a),o.value=[],s.value=null}finally{p.value=!1}}async function B(){if(i.value)try{await navigator.clipboard.writeText(i.value.content),M.notify({type:"positive",message:"HTML copiato negli appunti",position:"top-right"})}catch{M.notify({type:"negative",message:"Copia non riuscita",position:"top-right"})}}return I(async()=>{await T()}),(a,e)=>(r(),R(F,{class:"mail-debug-page"},{default:f(()=>[t("div",U,[e[5]||(e[5]=t("header",{class:"mail-debug-header"},[t("p",{class:"eyebrow"},"Developer tools"),t("h1",null,"Mail Debug"),t("p",{class:"subtitle"},[v(" Seleziona una mail da "),t("strong",null,"/maildebug"),v(" e visualizza l'HTML renderizzato. ")])],-1)),n(E,{flat:"",bordered:"",class:"mail-debug-card"},{default:f(()=>[n(x,{class:"controls"},{default:f(()=>[n(k,{color:"primary",icon:"refresh",label:"Aggiorna lista",loading:p.value,onClick:T},null,8,["loading"]),n(A,{modelValue:s.value,"onUpdate:modelValue":e[0]||(e[0]=l=>s.value=l),options:Q.value,"option-label":"label","option-value":"value","emit-value":"","map-options":"",outlined:"",dense:"",label:"Seleziona mail",class:"mail-select",disable:p.value||o.value.length===0},null,8,["modelValue","options","disable"])]),_:1}),n(H),n(x,null,{default:f(()=>[u.value?(r(),m("div",G,g(u.value),1)):i.value?(r(),m("div",W,[t("div",X,[e[3]||(e[3]=t("p",{class:"meta-label"},"Nome mail",-1)),t("h2",null,g(c.value.displayName),1),c.value.email?(r(),m("p",Y,[e[1]||(e[1]=t("strong",null,"Email:",-1)),v(" "+g(c.value.email),1)])):z("",!0),c.value.localDate?(r(),m("p",ee,[e[2]||(e[2]=t("strong",null,"Data locale:",-1)),v(" "+g(c.value.localDate),1)])):z("",!0),n(k,{flat:"",color:"secondary",icon:"content_copy",label:"Copia HTML",onClick:B})]),t("div",ae,[e[4]||(e[4]=t("p",{class:"meta-label"},"Render HTML",-1)),t("iframe",{class:"preview-frame",srcdoc:$.value,sandbox:"allow-popups allow-popups-to-escape-sandbox",title:"Mail HTML preview"},null,8,le)])])):(r(),m("div",J,"Nessuna mail selezionata."))]),_:1})]),_:1})])]),_:1}))}}),Ne=K(te,[["__scopeId","data-v-1b5b3a76"]]);export{Ne as default};
|
||||||
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1 @@
|
||||||
|
.lang-fallback[data-v-92823159]{display:inline-flex;align-items:center;justify-content:center;min-width:32px;height:22px;padding:0 4px;border:1px solid currentColor;border-radius:4px;font-size:10px;line-height:1;font-weight:700}.border[data-v-92823159]{border:1px solid #fff;border-radius:4px}.q-select i.q-icon[data-v-92823159]{color:#fff!important}
|
||||||
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1 @@
|
||||||
|
import{s as t,y as o,p as s,A as c}from"./index-QUdrNkKl.js";import{h as n}from"./render-B4qP-w0Q.js";import{u as l,a as i}from"./use-dark-BRt0_t6X.js";const p=t({name:"QCardSection",props:{tag:{type:String,default:"div"},horizontal:Boolean},setup(a,{slots:r}){const e=s(()=>`q-card__section q-card__section--${a.horizontal===!0?"horiz row no-wrap":"vert"}`);return()=>o(a.tag,{class:e.value},n(r.default))}}),g=t({name:"QCard",props:{...l,tag:{type:String,default:"div"},square:Boolean,flat:Boolean,bordered:Boolean},setup(a,{slots:r}){const{proxy:{$q:e}}=c(),d=i(a,e),u=s(()=>"q-card"+(d.value===!0?" q-card--dark q-dark":"")+(a.bordered===!0?" q-card--bordered":"")+(a.square===!0?" q-card--square no-border-radius":"")+(a.flat===!0?" q-card--flat no-shadow":""));return()=>o(a.tag,{class:u.value},n(r.default))}});export{g as Q,p as a};
|
||||||
|
|
@ -0,0 +1 @@
|
||||||
|
import{d as r,e}from"./QBtn-AYMizH8c.js";import{s as c,y as n,p as i}from"./index-QUdrNkKl.js";import{h as l}from"./render-B4qP-w0Q.js";const d=c({name:"QCardActions",props:{...r,vertical:Boolean},setup(s,{slots:a}){const o=e(s),t=i(()=>`q-card__actions ${o.value} q-card__actions--${s.vertical===!0?"vert column":"horiz row"}`);return()=>n("div",{class:t.value},l(a.default))}});export{d as Q};
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1 @@
|
||||||
|
import{s as v,y as r,p as a,A as w,q as f,_ as I,L as E}from"./index-QUdrNkKl.js";import{h as q,c as Q}from"./render-B4qP-w0Q.js";import{u as S,a as A}from"./use-dark-BRt0_t6X.js";import{g as K,h as R}from"./QBtn-AYMizH8c.js";const N=v({name:"QItemSection",props:{avatar:Boolean,thumbnail:Boolean,side:Boolean,top:Boolean,noWrap:Boolean},setup(e,{slots:n}){const l=a(()=>`q-item__section column q-item__section--${e.avatar===!0||e.side===!0||e.thumbnail===!0?"side":"main"}`+(e.top===!0?" q-item__section--top justify-start":" justify-center")+(e.avatar===!0?" q-item__section--avatar":"")+(e.thumbnail===!0?" q-item__section--thumbnail":"")+(e.noWrap===!0?" q-item__section--nowrap":""));return()=>r("div",{class:l.value},q(n.default))}}),P=v({name:"QItemLabel",props:{overline:Boolean,caption:Boolean,header:Boolean,lines:[Number,String]},setup(e,{slots:n}){const l=a(()=>parseInt(e.lines,10)),u=a(()=>"q-item__label"+(e.overline===!0?" q-item__label--overline text-overline":"")+(e.caption===!0?" q-item__label--caption text-caption":"")+(e.header===!0?" q-item__label--header":"")+(l.value===1?" ellipsis":"")),c=a(()=>e.lines!==void 0&&l.value>1?{overflow:"hidden",display:"-webkit-box","-webkit-box-orient":"vertical","-webkit-line-clamp":l.value}:null);return()=>r("div",{style:c.value,class:u.value},q(n.default))}}),O=v({name:"QItem",props:{...S,...K,tag:{type:String,default:"div"},active:{type:Boolean,default:null},clickable:Boolean,dense:Boolean,insetLevel:Number,tabindex:[String,Number],focused:Boolean,manualFocus:Boolean},emits:["click","keyup"],setup(e,{slots:n,emit:l}){const{proxy:{$q:u}}=w(),c=A(e,u),{hasLink:m,linkAttrs:k,linkClass:_,linkTag:h,navigateOnClick:y}=R(),s=f(null),o=f(null),d=a(()=>e.clickable===!0||m.value===!0||e.tag==="label"),i=a(()=>e.disable!==!0&&d.value===!0),g=a(()=>"q-item q-item-type row no-wrap"+(e.dense===!0?" q-item--dense":"")+(c.value===!0?" q-item--dark":"")+(m.value===!0&&e.active===null?_.value:e.active===!0?` q-item--active${e.activeClass!==void 0?` ${e.activeClass}`:""}`:"")+(e.disable===!0?" disabled":"")+(i.value===!0?" q-item--clickable q-link cursor-pointer "+(e.manualFocus===!0?"q-manual-focusable":"q-focusable q-hoverable")+(e.focused===!0?" q-manual-focusable--focused":""):"")),B=a(()=>e.insetLevel===void 0?null:{["padding"+(u.lang.rtl===!0?"Right":"Left")]:16+e.insetLevel*56+"px"});function x(t){i.value===!0&&(o.value!==null&&t.qAvoidFocus!==!0&&(t.qKeyEvent!==!0&&document.activeElement===s.value?o.value.focus():document.activeElement===o.value&&s.value.focus()),y(t))}function L(t){if(i.value===!0&&I(t,[13,32])===!0){E(t),t.qKeyEvent=!0;const b=new MouseEvent("click",t);b.qKeyEvent=!0,s.value.dispatchEvent(b)}l("keyup",t)}function C(){const t=Q(n.default,[]);return i.value===!0&&t.unshift(r("div",{class:"q-focus-helper",tabindex:-1,ref:o})),t}return()=>{const t={ref:s,class:g.value,style:B.value,role:"listitem",onClick:x,onKeyup:L};return i.value===!0?(t.tabindex=e.tabindex||"0",Object.assign(t,k.value)):d.value===!0&&(t["aria-disabled"]="true"),r(h.value,t,C())}}});export{O as Q,N as a,P as b};
|
||||||
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1 @@
|
||||||
|
import{s as p,A as g,M as r,N as t,O as h,V as d,y,p as s}from"./index-QUdrNkKl.js";import{h as f}from"./render-B4qP-w0Q.js";const Q=p({name:"QPage",props:{padding:Boolean,styleFn:Function},setup(a,{slots:i}){const{proxy:{$q:o}}=g(),e=r(h,t);if(e===t)return console.error("QPage needs to be a deep child of QLayout"),t;if(r(d,t)===t)return console.error("QPage needs to be child of QPageContainer"),t;const c=s(()=>{const n=(e.header.space===!0?e.header.size:0)+(e.footer.space===!0?e.footer.size:0);if(typeof a.styleFn=="function"){const l=e.isContainer.value===!0?e.containerHeight.value:o.screen.height;return a.styleFn(n,l)}return{minHeight:e.isContainer.value===!0?e.containerHeight.value-n+"px":o.screen.height===0?n!==0?`calc(100vh - ${n}px)`:"100vh":o.screen.height-n+"px"}}),u=s(()=>`q-page${a.padding===!0?" q-layout-padding":""}`);return()=>y("main",{class:u.value,style:c.value},f(i.default))}});export{Q};
|
||||||
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1 @@
|
||||||
|
import{Q as R,a as w}from"./QCard-D_vcm7k9.js";import{Q as h,r as I}from"./api-rhge6pbe.js";import{Q as f}from"./QInput-CEazYqyH.js";import{b as y,Q as A}from"./QBtn-AYMizH8c.js";import{Q as B}from"./QCardActions-DlFyQG4S.js";import{Q as S}from"./QPage-gf8hzrox.js";import{a as T,Y as N,q as t,o as g,e as U,w as n,h as m,f as s,k,t as _,Z as b,p as q}from"./index-QUdrNkKl.js";import{_ as L}from"./_plugin-vue_export-helper-DlAUqK2U.js";import"./render-B4qP-w0Q.js";import"./use-dark-BRt0_t6X.js";import"./use-key-composition-TTwP9QMZ.js";const E={class:"page-shell"},F={key:0,class:"msg msg-error"},M={key:1,class:"msg msg-success"},$=T({__name:"ResetPasswordPage",setup(D){const Q=N(),u=t(C()),r=t(""),d=t(""),p=t(!1),c=t(!1),v=t(!1),o=t(""),i=t(""),V=q(()=>u.value.trim().length>0?"Token caricato da URL, puoi comunque modificarlo.":"Inserisci il token ricevuto via email.");function C(){const e=Q.query.token;return typeof e=="string"?e:Array.isArray(e)&&e.length>0?String(e[0]):""}function P(){return o.value="",i.value="",u.value.trim()?r.value?r.value.length<8?(o.value="La password deve avere almeno 8 caratteri.",!1):r.value!==d.value?(o.value="Le password non coincidono.",!1):!0:(o.value="Inserisci una nuova password.",!1):(o.value="Token mancante.",!1)}async function x(){if(P()){p.value=!0,o.value="",i.value="";try{const e=await I({token:u.value.trim(),password:r.value});if(e.error){o.value=e.error;return}i.value=e.data?.message||"Password aggiornata con successo.",r.value="",d.value=""}catch(e){o.value=e instanceof Error?e.message:String(e)}finally{p.value=!1}}}return(e,a)=>(g(),U(S,{class:"reset-password-page"},{default:n(()=>[m("div",E,[s(R,{flat:"",bordered:"",class:"reset-card"},{default:n(()=>[s(w,{class:"card-head"},{default:n(()=>[...a[5]||(a[5]=[m("p",{class:"eyebrow"},"Account security",-1),m("h1",null,"Reset Password",-1),m("p",{class:"subtitle"},"Imposta una nuova password usando il token ricevuto via email.",-1)])]),_:1}),s(h),s(w,{class:"card-body"},{default:n(()=>[s(f,{modelValue:u.value,"onUpdate:modelValue":a[0]||(a[0]=l=>u.value=l),label:"Token",outlined:"",autogrow:"",type:"textarea",hint:V.value},null,8,["modelValue","hint"]),s(f,{modelValue:r.value,"onUpdate:modelValue":a[2]||(a[2]=l=>r.value=l),label:"Nuova password",outlined:"",type:c.value?"text":"password"},{append:n(()=>[s(y,{name:c.value?"visibility_off":"visibility",class:"cursor-pointer",onClick:a[1]||(a[1]=l=>c.value=!c.value)},null,8,["name"])]),_:1},8,["modelValue","type"]),s(f,{modelValue:d.value,"onUpdate:modelValue":a[4]||(a[4]=l=>d.value=l),label:"Conferma password",outlined:"",type:v.value?"text":"password"},{append:n(()=>[s(y,{name:v.value?"visibility_off":"visibility",class:"cursor-pointer",onClick:a[3]||(a[3]=l=>v.value=!v.value)},null,8,["name"])]),_:1},8,["modelValue","type"]),o.value?(g(),k("div",F,_(o.value),1)):b("",!0),i.value?(g(),k("div",M,_(i.value),1)):b("",!0)]),_:1}),s(B,{align:"right",class:"card-actions"},{default:n(()=>[s(A,{color:"primary",icon:"lock_reset",label:"Aggiorna password",loading:p.value,onClick:x},null,8,["loading"])]),_:1})]),_:1})])]),_:1}))}}),ee=L($,[["__scopeId","data-v-7f13b293"]]);export{ee as default};
|
||||||
|
|
@ -0,0 +1 @@
|
||||||
|
.reset-password-page[data-v-7f13b293]{min-height:100vh;padding:24px 14px;background:radial-gradient(circle at 88% 15%,#f8dfd0 0%,transparent 32%),radial-gradient(circle at 15% 10%,#d9f6f2 0%,transparent 36%),linear-gradient(140deg,#f6f3ee,#edf8f8)}.page-shell[data-v-7f13b293]{max-width:640px;margin:0 auto}.reset-card[data-v-7f13b293]{border-radius:14px;background:#ffffffdb}.card-head[data-v-7f13b293]{padding-bottom:10px}.eyebrow[data-v-7f13b293]{margin:0;letter-spacing:.18em;text-transform:uppercase;color:#345569;font-size:11px;font-weight:700}.card-head h1[data-v-7f13b293]{margin:4px 0;font-family:Space Grotesk,sans-serif;font-size:clamp(1.5rem,2.6vw,2rem)}.subtitle[data-v-7f13b293]{margin:0;color:#536979}.card-body[data-v-7f13b293]{display:grid;gap:12px}.msg[data-v-7f13b293]{border-radius:10px;padding:10px 12px;font-size:.95rem}.msg-error[data-v-7f13b293]{background:#fdeceb;color:#8f2222}.msg-success[data-v-7f13b293]{background:#e9f8ef;color:#1f6a3f}.card-actions[data-v-7f13b293]{padding:8px 16px 16px}
|
||||||
|
|
@ -0,0 +1 @@
|
||||||
|
const s=(t,r)=>{const o=t.__vccOpts||t;for(const[c,e]of r)o[c]=e;return o};export{s as _};
|
||||||
|
|
@ -0,0 +1 @@
|
||||||
|
import{u as w,a as y}from"./use-dark-BRt0_t6X.js";import{s as T,y as S,A as E,p as h}from"./index-QUdrNkKl.js";const b={true:"inset",item:"item-inset","item-thumbnail":"item-thumbnail-inset"},f={xs:2,sm:4,md:8,lg:16,xl:24},A=T({name:"QSeparator",props:{...w,spaced:[Boolean,String],inset:[Boolean,String],vertical:Boolean,color:String,size:String},setup(r){const t=E(),e=y(r,t.proxy.$q),a=h(()=>r.vertical===!0?"vertical":"horizontal"),s=h(()=>` q-separator--${a.value}`),i=h(()=>r.inset!==!1?`${s.value}-${b[r.inset]}`:""),l=h(()=>`q-separator${s.value}${i.value}`+(r.color!==void 0?` bg-${r.color}`:"")+(e.value===!0?" q-separator--dark":"")),m=h(()=>{const c={};if(r.size!==void 0&&(c[r.vertical===!0?"width":"height"]=r.size),r.spaced!==!1){const u=r.spaced===!0?`${f.md}px`:r.spaced in f?`${f[r.spaced]}px`:r.spaced,o=r.vertical===!0?["Left","Right"]:["Top","Bottom"];c[`margin${o[0]}`]=c[`margin${o[1]}`]=u}return c});return()=>S("hr",{class:l.value,style:m.value,"aria-orientation":a.value})}});function v(r){return typeof r=="object"&&r!==null&&Object.prototype.hasOwnProperty.call(r,"data")&&Object.prototype.hasOwnProperty.call(r,"error")}function g(r){return r instanceof DOMException&&r.name==="AbortError"?new Error("api.error.timeouterror"):r instanceof TypeError&&r.message==="Failed to fetch"?new Error("api.error.connectionerror"):r instanceof Error?r:new Error(String(r))}class O{apiUrl;localStorage;constructor(t){this.apiUrl=t,this.localStorage=window.localStorage}async request(t,e,a,s=7e3,i=!1){const l={"Cache-Control":"no-cache"};if(i||(l["Content-Type"]="application/json"),this.localStorage){const o=this.localStorage.getItem("Auth-Token");o&&(l["Auth-Token"]=o)}const m=new AbortController,c=setTimeout(()=>m.abort(),s),u={method:t,cache:"no-store",mode:"cors",credentials:"include",headers:l,signal:m.signal};i?u.body=a:a!=null&&(u.body=JSON.stringify(a));try{const o=await fetch(e,u);if(!o.ok)throw new Error("api.error."+o.statusText);if(this.localStorage){const d=o.headers.get("Auth-Token");d&&this.localStorage.setItem("Auth-Token",d)}const p=await o.json();if(!v(p))throw new Error("api.error.wrongdatatype");if(p.error)throw new Error(p.error);return p}catch(o){throw g(o)}finally{clearTimeout(c)}}processResult(t){return typeof t.data!="object"?{data:t.data,error:null}:(t.data||(t.data={}),{data:t.data,error:null})}processError(t){const e=g(t);return e.message==="api.error.timeouterror"?(Object.defineProperty(e,"__api_error__",{value:e.message,writable:!1}),{data:null,error:e.message}):e.message==="api.error.connectionerror"?(Object.defineProperty(e,"__api_error__",{value:e.message,writable:!1}),{data:null,error:e.message}):{data:null,error:e.message}}async POST(t,e,a){try{const s=t.includes("/upload/"),i=await this.request("POST",this.apiUrl+t,e,a,s);return this.processResult(i)}catch(s){return this.processError(s)}}async GET(t,e){try{const a=await this.request("GET",this.apiUrl+t,null,e);return this.processResult(a)}catch(a){return this.processError(a)}}async UPLOAD(t,e,a){try{const s=await this.request("POST",this.apiUrl+t,e,a,!0);return this.processResult(s)}catch(s){return this.processError(s)}}}const n=new O("http://localhost:3000"),_=async()=>await n.GET("/maildebug"),j=async r=>await n.POST("/admin/users",r),k=async r=>await n.POST("/auth/register",r),q=async()=>await n.GET("/metrics"),x=async r=>await n.POST("/auth/login",r),C=async r=>await n.POST("/auth/refresh",r),z=async r=>await n.POST("/auth/password/forgot",r),D=async r=>await n.POST("/auth/password/reset",r),R=async()=>await n.GET("/health"),U=async()=>await n.GET("/auth/me");export{A as Q,C as a,j as b,U as c,k as d,_ as e,z as f,R as h,x as l,q as m,D as r};
|
||||||
Binary file not shown.
Binary file not shown.
|
|
@ -0,0 +1 @@
|
||||||
|
import{ab as l}from"./index-QUdrNkKl.js";function r(){if(window.getSelection!==void 0){const t=window.getSelection();t.empty!==void 0?t.empty():t.removeAllRanges!==void 0&&(t.removeAllRanges(),l.is.mobile!==!0&&t.addRange(document.createRange()))}else document.selection!==void 0&&document.selection.empty()}function a(t,e,o){return o<=e?e:Math.min(o,Math.max(e,t))}function s(t,e,o){if(o<=e)return e;const i=o-e+1;let n=e+(t-e)%i;return n<e&&(n=i+n),n===0?0:n}export{a as b,r as c,s as n};
|
||||||
|
|
@ -0,0 +1 @@
|
||||||
|
import{d as a,c as o,r as c,l as n}from"./index-QUdrNkKl.js";const t={failed:"Action failed",success:"Action was successful"},l={"en-US":t},d=a(({app:e})=>{const s=o({locale:c(n()),messages:l});e.use(s)});export{d as default};
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1 @@
|
||||||
|
import{y as c,R as f}from"./index-QUdrNkKl.js";function v(n,i){return n!==void 0&&n()||i}function d(n,i){if(n!==void 0){const r=n();if(r!=null)return r.slice()}return i}function h(n,i){return n!==void 0?i.concat(n()):i}function S(n,i){return n===void 0?i:i!==void 0?i.concat(n()):n()}function l(n,i,r,o,t,u){i.key=o+t;const e=c(n,i,r);return t===!0?f(e,u()):e}export{S as a,l as b,d as c,h as d,v as h};
|
||||||
|
|
@ -0,0 +1 @@
|
||||||
|
import{p as e}from"./index-QUdrNkKl.js";const u={dark:{type:Boolean,default:null}};function o(a,r){return e(()=>a.dark===null?r.dark.isActive:a.dark)}export{o as a,u};
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1 @@
|
||||||
|
import{v as u}from"./QBtn-AYMizH8c.js";import{a6 as i,Q as m,A as s}from"./index-QUdrNkKl.js";function f(){let e=null;const o=s();function t(){e!==null&&(clearTimeout(e),e=null)}return i(t),m(t),{removeTimeout:t,registerTimeout(n,r){t(),u(o)===!1&&(e=setTimeout(()=>{e=null,n()},r))}}}export{f as u};
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 63 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 12 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 859 B |
Binary file not shown.
|
After Width: | Height: | Size: 2.0 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 9.4 KiB |
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1,17 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="it">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>Recupero password</title>
|
||||||
|
</head>
|
||||||
|
<body style="font-family: Arial, sans-serif; color: #1f2937; line-height: 1.5;">
|
||||||
|
<h1 style="margin-bottom: 16px;">Recupero password</h1>
|
||||||
|
<p>Ciao {{.UserName}},</p>
|
||||||
|
<p>abbiamo ricevuto una richiesta di reset password per l'account <strong>{{.UserEmail}}</strong>.</p>
|
||||||
|
<p>Usa questo token per completare il reset:</p>
|
||||||
|
<p style="font-size: 20px; font-weight: bold;">{{.ResetToken}}</p>
|
||||||
|
<p>Oppure apri questo link:</p>
|
||||||
|
<p><a href="{{.ResetURL}}">{{.ResetURL}}</a></p>
|
||||||
|
<p>Il token scade tra 30 minuti. Se non hai richiesto il reset, ignora questa email.</p>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
Ciao {{.UserName}},
|
||||||
|
|
||||||
|
abbiamo ricevuto una richiesta di reset password per l'account {{.UserEmail}}.
|
||||||
|
|
||||||
|
Token reset:
|
||||||
|
{{.ResetToken}}
|
||||||
|
|
||||||
|
Link reset:
|
||||||
|
{{.ResetURL}}
|
||||||
|
|
||||||
|
Il token scade tra 30 minuti. Se non hai richiesto il reset, ignora questa email.
|
||||||
|
|
@ -0,0 +1,13 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="it">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>Registrazione completata</title>
|
||||||
|
</head>
|
||||||
|
<body style="font-family: Arial, sans-serif; color: #1f2937; line-height: 1.5;">
|
||||||
|
<h1 style="margin-bottom: 16px;">Benvenuto su {{.AppName}}</h1>
|
||||||
|
<p>Ciao {{.UserName}},</p>
|
||||||
|
<p>la registrazione per l'account <strong>{{.UserEmail}}</strong> e stata completata correttamente.</p>
|
||||||
|
<p>Se non hai richiesto tu questa registrazione, contatta subito il supporto.</p>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|
@ -0,0 +1,5 @@
|
||||||
|
Ciao {{.UserName}},
|
||||||
|
|
||||||
|
la registrazione per l'account {{.UserEmail}} su {{.AppName}} e stata completata correttamente.
|
||||||
|
|
||||||
|
Se non hai richiesto tu questa registrazione, contatta subito il supporto.
|
||||||
|
|
@ -0,0 +1,233 @@
|
||||||
|
package mail
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"fmt"
|
||||||
|
"html/template"
|
||||||
|
"net"
|
||||||
|
"net/smtp"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
texttemplate "text/template"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
AppName string
|
||||||
|
Mode string
|
||||||
|
From string
|
||||||
|
DebugDir string
|
||||||
|
TemplatesDir string
|
||||||
|
FrontendBaseURL string
|
||||||
|
ResetPasswordPath string
|
||||||
|
SMTP SMTPConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
type SMTPConfig struct {
|
||||||
|
Host string
|
||||||
|
Port int
|
||||||
|
Username string
|
||||||
|
Password string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Message struct {
|
||||||
|
To string
|
||||||
|
Subject string
|
||||||
|
Template string
|
||||||
|
TemplateData any
|
||||||
|
}
|
||||||
|
|
||||||
|
type Service struct {
|
||||||
|
cfg Config
|
||||||
|
}
|
||||||
|
|
||||||
|
type TemplateData struct {
|
||||||
|
AppName string
|
||||||
|
UserName string
|
||||||
|
UserEmail string
|
||||||
|
ResetURL string
|
||||||
|
ResetToken string
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(cfg Config) (*Service, error) {
|
||||||
|
if cfg.Mode != "smtp" && cfg.Mode != "file" {
|
||||||
|
return nil, fmt.Errorf("unsupported mail mode %q", cfg.Mode)
|
||||||
|
}
|
||||||
|
if cfg.From == "" {
|
||||||
|
return nil, fmt.Errorf("mail sender is required")
|
||||||
|
}
|
||||||
|
if cfg.AppName == "" {
|
||||||
|
cfg.AppName = "Application"
|
||||||
|
}
|
||||||
|
if cfg.TemplatesDir == "" {
|
||||||
|
return nil, fmt.Errorf("mail templates directory is required")
|
||||||
|
}
|
||||||
|
if cfg.Mode == "file" {
|
||||||
|
if cfg.DebugDir == "" {
|
||||||
|
return nil, fmt.Errorf("mail debug directory is required")
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(cfg.DebugDir, 0o755); err != nil {
|
||||||
|
return nil, fmt.Errorf("create mail debug directory: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if cfg.Mode == "smtp" {
|
||||||
|
if cfg.SMTP.Host == "" || cfg.SMTP.Port <= 0 {
|
||||||
|
return nil, fmt.Errorf("smtp host and port are required")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return &Service{cfg: cfg}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) Send(ctx context.Context, msg Message) error {
|
||||||
|
htmlBody, textBody, err := s.renderBodies(msg.Template, msg.TemplateData)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
rawMessage := buildMessage(s.cfg.From, msg.To, msg.Subject, textBody, htmlBody)
|
||||||
|
switch s.cfg.Mode {
|
||||||
|
case "smtp":
|
||||||
|
return s.sendSMTP(ctx, msg.To, rawMessage)
|
||||||
|
case "file":
|
||||||
|
return s.writeDebugMail(msg.To, msg.Subject, rawMessage)
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("unsupported mail mode %q", s.cfg.Mode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) ResetLink(token string) string {
|
||||||
|
base := strings.TrimRight(s.cfg.FrontendBaseURL, "/")
|
||||||
|
path := s.cfg.ResetPasswordPath
|
||||||
|
if path == "" {
|
||||||
|
path = "/#reset-password"
|
||||||
|
}
|
||||||
|
if token == "" {
|
||||||
|
return base + path
|
||||||
|
}
|
||||||
|
if base == "" {
|
||||||
|
return path + "?token=" + token
|
||||||
|
}
|
||||||
|
return base + path + "?token=" + token
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) AppName() string {
|
||||||
|
return s.cfg.AppName
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) renderBodies(templateName string, data any) (string, string, error) {
|
||||||
|
htmlPath := filepath.Join(s.cfg.TemplatesDir, templateName+".html.tmpl")
|
||||||
|
textPath := filepath.Join(s.cfg.TemplatesDir, templateName+".txt.tmpl")
|
||||||
|
|
||||||
|
htmlTpl, err := template.ParseFiles(htmlPath)
|
||||||
|
if err != nil {
|
||||||
|
return "", "", fmt.Errorf("parse html template %s: %w", htmlPath, err)
|
||||||
|
}
|
||||||
|
textTpl, err := texttemplate.ParseFiles(textPath)
|
||||||
|
if err != nil {
|
||||||
|
return "", "", fmt.Errorf("parse text template %s: %w", textPath, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var htmlBuf bytes.Buffer
|
||||||
|
if err := htmlTpl.Execute(&htmlBuf, data); err != nil {
|
||||||
|
return "", "", fmt.Errorf("execute html template %s: %w", htmlPath, err)
|
||||||
|
}
|
||||||
|
var textBuf bytes.Buffer
|
||||||
|
if err := textTpl.Execute(&textBuf, data); err != nil {
|
||||||
|
return "", "", fmt.Errorf("execute text template %s: %w", textPath, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return htmlBuf.String(), textBuf.String(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildMessage(from, to, subject, textBody, htmlBody string) []byte {
|
||||||
|
boundary := fmt.Sprintf("mixed-%d", time.Now().UnixNano())
|
||||||
|
headers := []string{
|
||||||
|
"MIME-Version: 1.0",
|
||||||
|
fmt.Sprintf("From: %s", from),
|
||||||
|
fmt.Sprintf("To: %s", to),
|
||||||
|
fmt.Sprintf("Subject: %s", subject),
|
||||||
|
fmt.Sprintf("Content-Type: multipart/alternative; boundary=%q", boundary),
|
||||||
|
"",
|
||||||
|
}
|
||||||
|
|
||||||
|
body := []string{
|
||||||
|
fmt.Sprintf("--%s", boundary),
|
||||||
|
"Content-Type: text/plain; charset=UTF-8",
|
||||||
|
"Content-Transfer-Encoding: 8bit",
|
||||||
|
"",
|
||||||
|
textBody,
|
||||||
|
fmt.Sprintf("--%s", boundary),
|
||||||
|
"Content-Type: text/html; charset=UTF-8",
|
||||||
|
"Content-Transfer-Encoding: 8bit",
|
||||||
|
"",
|
||||||
|
htmlBody,
|
||||||
|
fmt.Sprintf("--%s--", boundary),
|
||||||
|
"",
|
||||||
|
}
|
||||||
|
|
||||||
|
return []byte(strings.Join(append(headers, body...), "\r\n"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) sendSMTP(ctx context.Context, to string, raw []byte) error {
|
||||||
|
addr := fmt.Sprintf("%s:%d", s.cfg.SMTP.Host, s.cfg.SMTP.Port)
|
||||||
|
dialer := &net.Dialer{}
|
||||||
|
conn, err := dialer.DialContext(ctx, "tcp", addr)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("dial smtp server: %w", err)
|
||||||
|
}
|
||||||
|
defer conn.Close()
|
||||||
|
|
||||||
|
client, err := smtp.NewClient(conn, s.cfg.SMTP.Host)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("create smtp client: %w", err)
|
||||||
|
}
|
||||||
|
defer client.Close()
|
||||||
|
|
||||||
|
if ok, _ := client.Extension("STARTTLS"); ok {
|
||||||
|
tlsCfg := &tls.Config{ServerName: s.cfg.SMTP.Host}
|
||||||
|
if err := client.StartTLS(tlsCfg); err != nil {
|
||||||
|
return fmt.Errorf("starttls: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if s.cfg.SMTP.Username != "" {
|
||||||
|
auth := smtp.PlainAuth("", s.cfg.SMTP.Username, s.cfg.SMTP.Password, s.cfg.SMTP.Host)
|
||||||
|
if err := client.Auth(auth); err != nil {
|
||||||
|
return fmt.Errorf("smtp auth: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := client.Mail(s.cfg.From); err != nil {
|
||||||
|
return fmt.Errorf("smtp mail from: %w", err)
|
||||||
|
}
|
||||||
|
if err := client.Rcpt(to); err != nil {
|
||||||
|
return fmt.Errorf("smtp rcpt to: %w", err)
|
||||||
|
}
|
||||||
|
wc, err := client.Data()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("smtp data: %w", err)
|
||||||
|
}
|
||||||
|
if _, err := wc.Write(raw); err != nil {
|
||||||
|
_ = wc.Close()
|
||||||
|
return fmt.Errorf("write smtp message: %w", err)
|
||||||
|
}
|
||||||
|
if err := wc.Close(); err != nil {
|
||||||
|
return fmt.Errorf("close smtp message: %w", err)
|
||||||
|
}
|
||||||
|
if err := client.Quit(); err != nil {
|
||||||
|
return fmt.Errorf("smtp quit: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) writeDebugMail(to, subject string, raw []byte) error {
|
||||||
|
safeRecipient := strings.NewReplacer("@", "_at_", "/", "_", "\\", "_", ":", "_", " ", "_").Replace(to)
|
||||||
|
filename := fmt.Sprintf("%d_%s.eml", time.Now().UnixNano(), safeRecipient)
|
||||||
|
path := filepath.Join(s.cfg.DebugDir, filename)
|
||||||
|
if err := os.WriteFile(path, raw, 0o644); err != nil {
|
||||||
|
return fmt.Errorf("write debug mail %s: %w", path, err)
|
||||||
|
}
|
||||||
|
_ = subject
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,213 @@
|
||||||
|
package models
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// UserRoles is stored as JSON array of strings.
|
||||||
|
|
||||||
|
// Typescript: type
|
||||||
|
type UserRoles []string
|
||||||
|
|
||||||
|
// Typescript: type
|
||||||
|
type UsersShort []UserShort
|
||||||
|
|
||||||
|
type User struct {
|
||||||
|
ID int `json:"id" gorm:"primaryKey"`
|
||||||
|
Email string `json:"email" gorm:"uniqueIndex;size:255"`
|
||||||
|
Name string `json:"name" gorm:"size:255"`
|
||||||
|
Password string `json:"password" gorm:"size:255"`
|
||||||
|
Roles UserRoles `json:"roles" gorm:"type:text;serializer:json"`
|
||||||
|
Types UserTypes `json:"types" gorm:"type:text;serializer:json"`
|
||||||
|
Status UserStatus `json:"status" gorm:"type:text;default:'pending'"`
|
||||||
|
ActivatedAt *time.Time `json:"activatedAt" ts:"type=Date"`
|
||||||
|
UUID string `json:"uuid" gorm:"size:36"`
|
||||||
|
Details *UserDetails `json:"details" gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
|
||||||
|
Preferences *UserPreferences `json:"preferences" gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
|
||||||
|
Avatar *string `json:"avatar" gorm:"size:512"`
|
||||||
|
CreatedAt time.Time `json:"createdAt" ts:"type=Date"`
|
||||||
|
UpdatedAt time.Time `json:"updatedAt" ts:"type=Date"`
|
||||||
|
DeletedAt gorm.DeletedAt `json:"-" gorm:"index" ts:"type=Date"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// UserCreateInput captures the minimal payload to create a user.
|
||||||
|
|
||||||
|
// Typescript: interface
|
||||||
|
type UserCreateInput struct {
|
||||||
|
Name string `json:"name" validate:"required,min=1,max=255"`
|
||||||
|
Email string `json:"email" validate:"required,email"`
|
||||||
|
Password string `json:"password" validate:"required,min=8,max=128"`
|
||||||
|
Roles UserRoles `json:"roles"`
|
||||||
|
Status UserStatus `json:"status"`
|
||||||
|
Types UserTypes `json:"types"`
|
||||||
|
Avatar *string `json:"avatar"`
|
||||||
|
Details *UserDetailsShort `json:"details" `
|
||||||
|
Preferences *UserPreferencesShort `json:"preferences" `
|
||||||
|
}
|
||||||
|
|
||||||
|
// UserTypes is stored as JSON array (e.g. ["internal","external"]).
|
||||||
|
type UserTypes []string
|
||||||
|
|
||||||
|
// UserShort is a lightweight representation of User without sensitive data.
|
||||||
|
|
||||||
|
// Typescript: interface
|
||||||
|
type UserShort struct {
|
||||||
|
Email string `json:"email" `
|
||||||
|
Name string `json:"name" `
|
||||||
|
Roles UserRoles `json:"roles" `
|
||||||
|
Status UserStatus `json:"status" `
|
||||||
|
UUID string `json:"uuid" `
|
||||||
|
Details *UserDetailsShort `json:"details" `
|
||||||
|
Preferences *UserPreferencesShort `json:"preferences" `
|
||||||
|
Avatar *string `json:"avatar" `
|
||||||
|
}
|
||||||
|
|
||||||
|
// ToUserShort maps a User to the lightweight view.
|
||||||
|
func ToUserShort(u *User) UserShort {
|
||||||
|
if u == nil {
|
||||||
|
return UserShort{}
|
||||||
|
}
|
||||||
|
return UserShort{
|
||||||
|
Email: u.Email,
|
||||||
|
Name: u.Name,
|
||||||
|
Roles: u.Roles,
|
||||||
|
Status: u.Status,
|
||||||
|
UUID: u.UUID,
|
||||||
|
Details: ToUserDetailsShort(u.Details),
|
||||||
|
Preferences: ToUserPreferencesShort(u.Preferences),
|
||||||
|
Avatar: u.Avatar,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ToUserDetailsShort maps UserDetails to the short version.
|
||||||
|
func ToUserDetailsShort(d *UserDetails) *UserDetailsShort {
|
||||||
|
if d == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &UserDetailsShort{
|
||||||
|
Title: d.Title,
|
||||||
|
FirstName: d.FirstName,
|
||||||
|
LastName: d.LastName,
|
||||||
|
Address: d.Address,
|
||||||
|
City: d.City,
|
||||||
|
ZipCode: d.ZipCode,
|
||||||
|
Country: d.Country,
|
||||||
|
Phone: d.Phone,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ToUserPreferencesShort maps UserPreferences to the short version.
|
||||||
|
func ToUserPreferencesShort(p *UserPreferences) *UserPreferencesShort {
|
||||||
|
if p == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &UserPreferencesShort{
|
||||||
|
UseIdle: p.UseIdle,
|
||||||
|
IdleTimeout: p.IdleTimeout,
|
||||||
|
UseIdlePassword: p.UseIdlePassword,
|
||||||
|
IdlePin: p.IdlePin,
|
||||||
|
UseDirectLogin: p.UseDirectLogin,
|
||||||
|
UseQuadcodeLogin: p.UseQuadcodeLogin,
|
||||||
|
SendNoticesMail: p.SendNoticesMail,
|
||||||
|
Language: p.Language,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// UserPreferences holds per-user settings stored as JSON.
|
||||||
|
type UserPreferences struct {
|
||||||
|
ID int `json:"id" gorm:"primaryKey"`
|
||||||
|
UserID int `json:"userId" gorm:"index"`
|
||||||
|
UseIdle bool `json:"useIdle"`
|
||||||
|
IdleTimeout int `json:"idleTimeout"`
|
||||||
|
UseIdlePassword bool `json:"useIdlePassword"`
|
||||||
|
IdlePin string `json:"idlePin"`
|
||||||
|
UseDirectLogin bool `json:"useDirectLogin"`
|
||||||
|
UseQuadcodeLogin bool `json:"useQuadcodeLogin"`
|
||||||
|
SendNoticesMail bool `json:"sendNoticesMail"`
|
||||||
|
Language string `json:"language"`
|
||||||
|
CreatedAt time.Time `json:"createdAt" ts:"type=Date"`
|
||||||
|
UpdatedAt time.Time `json:"updatedAt" ts:"type=Date"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// UserPreferences holds per-user settings stored as JSON.
|
||||||
|
|
||||||
|
// Typescript: interface
|
||||||
|
type UserPreferencesShort struct {
|
||||||
|
UseIdle bool `json:"useIdle"`
|
||||||
|
IdleTimeout int `json:"idleTimeout"`
|
||||||
|
UseIdlePassword bool `json:"useIdlePassword"`
|
||||||
|
IdlePin string `json:"idlePin"`
|
||||||
|
UseDirectLogin bool `json:"useDirectLogin"`
|
||||||
|
UseQuadcodeLogin bool `json:"useQuadcodeLogin"`
|
||||||
|
SendNoticesMail bool `json:"sendNoticesMail"`
|
||||||
|
Language string `json:"language"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// UserDetails holds optional profile data.
|
||||||
|
type UserDetails struct {
|
||||||
|
ID int `json:"id" gorm:"primaryKey"`
|
||||||
|
UserID int `json:"userId" gorm:"index"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
FirstName string `json:"firstName"`
|
||||||
|
LastName string `json:"lastName"`
|
||||||
|
Address string `json:"address"`
|
||||||
|
City string `json:"city"`
|
||||||
|
ZipCode string `json:"zipCode"`
|
||||||
|
Country string `json:"country"`
|
||||||
|
Phone string `json:"phone"`
|
||||||
|
CreatedAt time.Time `json:"createdAt" ts:"type=Date"`
|
||||||
|
UpdatedAt time.Time `json:"updatedAt" ts:"type=Date"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// UserDetails holds optional profile data.
|
||||||
|
|
||||||
|
// Typescript: interface
|
||||||
|
type UserDetailsShort struct {
|
||||||
|
Title string `json:"title"`
|
||||||
|
FirstName string `json:"firstName"`
|
||||||
|
LastName string `json:"lastName"`
|
||||||
|
Address string `json:"address"`
|
||||||
|
City string `json:"city"`
|
||||||
|
ZipCode string `json:"zipCode"`
|
||||||
|
Country string `json:"country"`
|
||||||
|
Phone string `json:"phone"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Session tracks logins with browser metadata.
|
||||||
|
|
||||||
|
type Session struct {
|
||||||
|
ID int `json:"id" gorm:"primaryKey"`
|
||||||
|
UserID *int `json:"userId" gorm:"index"`
|
||||||
|
Username string `json:"username" gorm:"size:255"`
|
||||||
|
AccessTokenHash string `json:"-" gorm:"size:128;index"`
|
||||||
|
RefreshTokenHash string `json:"-" gorm:"size:128;index"`
|
||||||
|
ExpiresAt time.Time `json:"expiresAt" ts:"type=Date" gorm:"index"`
|
||||||
|
IPAddress string `json:"ipAddress" gorm:"size:64"`
|
||||||
|
UserAgent string `json:"userAgent" gorm:"size:512"`
|
||||||
|
CreatedAt time.Time `json:"createdAt" ts:"type=Date"`
|
||||||
|
UpdatedAt time.Time `json:"updatedAt" ts:"type=Date"`
|
||||||
|
DeletedAt gorm.DeletedAt `json:"-" gorm:"index" `
|
||||||
|
}
|
||||||
|
|
||||||
|
type PasswordResetToken struct {
|
||||||
|
ID int `json:"id" gorm:"primaryKey"`
|
||||||
|
UserID int `json:"userId" gorm:"index"`
|
||||||
|
TokenHash string `json:"-" gorm:"size:64;uniqueIndex"`
|
||||||
|
ExpiresAt time.Time `json:"expiresAt" ts:"type=Date" gorm:"index"`
|
||||||
|
UsedAt *time.Time `json:"usedAt" ts:"type=Date"`
|
||||||
|
CreatedAt time.Time `json:"createdAt" ts:"type=Date"`
|
||||||
|
UpdatedAt time.Time `json:"updatedAt" ts:"type=Date"`
|
||||||
|
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// UserStatus represents lifecycle state of a user.
|
||||||
|
type UserStatus string
|
||||||
|
|
||||||
|
// Typescript: enum=UserStatus
|
||||||
|
const (
|
||||||
|
UserStatusPending UserStatus = "pending"
|
||||||
|
UserStatusActive UserStatus = "active"
|
||||||
|
UserStatusDisabled UserStatus = "disabled"
|
||||||
|
)
|
||||||
|
|
@ -0,0 +1,26 @@
|
||||||
|
package roles
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
"server/internal/http/controllers"
|
||||||
|
"server/internal/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
func CheckUserRoleConsistency(db *gorm.DB, resolver *controllers.RoleResolver) {
|
||||||
|
var list []models.User
|
||||||
|
if err := db.Select("email", "roles").Find(&list).Error; err != nil {
|
||||||
|
log.Printf("warning: cannot verify user roles: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, u := range list {
|
||||||
|
for _, r := range u.Roles {
|
||||||
|
if !resolver.RoleDefined(r) {
|
||||||
|
log.Printf("inconsistency: user %s has undefined role %q", u.Email, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,104 @@
|
||||||
|
package seed
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/hex"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/brianvoe/gofakeit/v6"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
"server/internal/auth"
|
||||||
|
"server/internal/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Credential exposes the plaintext password generated for a seeded user.
|
||||||
|
type Credential struct {
|
||||||
|
Email string
|
||||||
|
Password string
|
||||||
|
}
|
||||||
|
|
||||||
|
// SeedUsers generates n fake users and persists them. Returns the created slice.
|
||||||
|
func SeedUsers(db *gorm.DB, n int) ([]models.User, []Credential, error) {
|
||||||
|
if n <= 0 {
|
||||||
|
return nil, nil, fmt.Errorf("seed size must be greater than zero")
|
||||||
|
}
|
||||||
|
|
||||||
|
gofakeit.Seed(time.Now().UnixNano())
|
||||||
|
|
||||||
|
items := make([]models.User, 0, n)
|
||||||
|
creds := make([]Credential, 0, n)
|
||||||
|
for i := 0; i < n; i++ {
|
||||||
|
now := time.Now().UTC()
|
||||||
|
uuid := gofakeit.UUID()
|
||||||
|
email := gofakeit.Email()
|
||||||
|
|
||||||
|
pw, err := randomPassword()
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, fmt.Errorf("generate password: %w", err)
|
||||||
|
}
|
||||||
|
passwordHash, err := auth.HashPassword(pw)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, fmt.Errorf("hash seed password: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
item := models.User{
|
||||||
|
Email: email,
|
||||||
|
Name: gofakeit.Name(),
|
||||||
|
Password: passwordHash,
|
||||||
|
Roles: models.UserRoles{"user"},
|
||||||
|
Status: models.UserStatusActive,
|
||||||
|
Types: models.UserTypes{"internal"},
|
||||||
|
UUID: uuid,
|
||||||
|
Details: &models.UserDetails{
|
||||||
|
Title: gofakeit.JobTitle(),
|
||||||
|
FirstName: gofakeit.FirstName(),
|
||||||
|
LastName: gofakeit.LastName(),
|
||||||
|
Phone: gofakeit.Phone(),
|
||||||
|
Address: gofakeit.Street(),
|
||||||
|
City: gofakeit.City(),
|
||||||
|
ZipCode: gofakeit.Zip(),
|
||||||
|
Country: gofakeit.Country(),
|
||||||
|
},
|
||||||
|
Preferences: &models.UserPreferences{
|
||||||
|
UseIdle: gofakeit.Bool(),
|
||||||
|
IdleTimeout: gofakeit.Number(1, 30),
|
||||||
|
UseIdlePassword: gofakeit.Bool(),
|
||||||
|
IdlePin: gofakeit.DigitN(6),
|
||||||
|
UseDirectLogin: gofakeit.Bool(),
|
||||||
|
UseQuadcodeLogin: gofakeit.Bool(),
|
||||||
|
SendNoticesMail: gofakeit.Bool(),
|
||||||
|
Language: gofakeit.Language(),
|
||||||
|
},
|
||||||
|
Avatar: nil,
|
||||||
|
CreatedAt: now,
|
||||||
|
UpdatedAt: now,
|
||||||
|
ActivatedAt: func() *time.Time {
|
||||||
|
ts := now
|
||||||
|
return &ts
|
||||||
|
}(),
|
||||||
|
}
|
||||||
|
|
||||||
|
items = append(items, item)
|
||||||
|
creds = append(creds, Credential{
|
||||||
|
Email: email,
|
||||||
|
Password: pw,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := db.Create(&items).Error; err != nil {
|
||||||
|
return nil, nil, fmt.Errorf("insert users: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return items, creds, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func randomPassword() (string, error) {
|
||||||
|
buf := make([]byte, 12)
|
||||||
|
if _, err := rand.Read(buf); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
// hex-encoded -> 24 characters.
|
||||||
|
return hex.EncodeToString(buf), nil
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,80 @@
|
||||||
|
package tsgenerator
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
|
||||||
|
"server/internal/config"
|
||||||
|
tsrpc "server/pkg/ts-rpc"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TsGenerate() (string, error) {
|
||||||
|
path := "GeneratedCode"
|
||||||
|
if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
|
||||||
|
err := os.Mkdir(path, os.ModePerm)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("create GeneratedCode directory: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var tsSource = tsrpc.GetTSSource(tsrpc.TSConfig{Url: "http://localhost:3000", TsApi: nil, Path: "."})
|
||||||
|
|
||||||
|
formatted, err1 := formatJS(tsSource)
|
||||||
|
if err1 != nil {
|
||||||
|
return "", err1
|
||||||
|
}
|
||||||
|
|
||||||
|
err := os.WriteFile("GeneratedCode/generatedTypescript.ts", []byte(formatted), 0644)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("write local generated typescript: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
configPath := os.Getenv("CONFIG_PATH")
|
||||||
|
if configPath == "" {
|
||||||
|
configPath = "configs/config.json"
|
||||||
|
}
|
||||||
|
if _, err := config.LoadConfig(configPath); err != nil {
|
||||||
|
return "", fmt.Errorf("load config from %s: %w", configPath, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
frontendAPIPath := os.Getenv("FRONTEND_API_PATH")
|
||||||
|
if frontendAPIPath == "" {
|
||||||
|
return "", errors.New("FRONTEND_API_PATH must be set")
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("Saving generated TypeScript to %s\n", frontendAPIPath)
|
||||||
|
|
||||||
|
err = os.WriteFile(frontendAPIPath+"/api.ts", []byte(formatted), 0644)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("write frontend api.ts: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return formatted, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func formatJS(src string) (string, error) {
|
||||||
|
// Se hai prettier globale:
|
||||||
|
cmd := exec.Command("prettier", "--parser", "typescript", "--use-tabs", "false", "--tab-width", "2")
|
||||||
|
|
||||||
|
// Se hai prettier solo come devDependency:
|
||||||
|
// cmd := exec.Command("npx", "prettier", "--parser", "typescript")
|
||||||
|
|
||||||
|
cmd.Stdin = bytes.NewBufferString(src)
|
||||||
|
|
||||||
|
var out bytes.Buffer
|
||||||
|
var stderr bytes.Buffer
|
||||||
|
cmd.Stdout = &out
|
||||||
|
cmd.Stderr = &stderr
|
||||||
|
|
||||||
|
err := cmd.Run()
|
||||||
|
if err != nil {
|
||||||
|
// Stampa anche lo stderr di Prettier, così vedi l’errore reale
|
||||||
|
return "", fmt.Errorf("prettier error: %v\nstderr: %s", err, stderr.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
return out.String(), nil
|
||||||
|
|
||||||
|
}
|
||||||
Binary file not shown.
|
|
@ -0,0 +1,661 @@
|
||||||
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU Affero General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works, specifically designed to ensure
|
||||||
|
cooperation with the community in the case of network server software.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
our General Public Licenses are intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
Developers that use our General Public Licenses protect your rights
|
||||||
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
|
you this License which gives you legal permission to copy, distribute
|
||||||
|
and/or modify the software.
|
||||||
|
|
||||||
|
A secondary benefit of defending all users' freedom is that
|
||||||
|
improvements made in alternate versions of the program, if they
|
||||||
|
receive widespread use, become available for other developers to
|
||||||
|
incorporate. Many developers of free software are heartened and
|
||||||
|
encouraged by the resulting cooperation. However, in the case of
|
||||||
|
software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and
|
||||||
|
letting the public access it on a server without ever releasing its
|
||||||
|
source code to the public.
|
||||||
|
|
||||||
|
The GNU Affero General Public License is designed specifically to
|
||||||
|
ensure that, in such cases, the modified source code becomes available
|
||||||
|
to the community. It requires the operator of a network server to
|
||||||
|
provide the source code of the modified version running there to the
|
||||||
|
users of that server. Therefore, public use of a modified version, on
|
||||||
|
a publicly accessible server, gives the public access to the source
|
||||||
|
code of the modified version.
|
||||||
|
|
||||||
|
An older license, called the Affero General Public License and
|
||||||
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
|
a different license, not a version of the Affero GPL, but Affero has
|
||||||
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
|
this license.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the
|
||||||
|
Program, your modified version must prominently offer all users
|
||||||
|
interacting with it remotely through a computer network (if your version
|
||||||
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
|
Source of your version by providing access to the Corresponding Source
|
||||||
|
from a network server at no charge, through some standard or customary
|
||||||
|
means of facilitating copying of software. This Corresponding Source
|
||||||
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
|
following paragraph.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the work with which it is combined will remain governed by version
|
||||||
|
3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU Affero General Public License from time to time. Such new versions
|
||||||
|
will be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU Affero General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU Affero General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU Affero General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as published
|
||||||
|
by the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If your software can interact with users remotely through a computer
|
||||||
|
network, you should also make sure that it provides a way for users to
|
||||||
|
get its source. For example, if your program is a web application, its
|
||||||
|
interface could display a "Source" link that leads users to an archive
|
||||||
|
of the code. There are many ways you could offer source, and different
|
||||||
|
solutions will be better for different programs; see section 13 for the
|
||||||
|
specific requirements.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
@ -0,0 +1,54 @@
|
||||||
|
# ts-rpc
|
||||||
|
|
||||||
|
#### typescript RPC
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
##### The ghost bridge from front-end to backend
|
||||||
|
|
||||||
|
This project is a POC - Proof of concept.
|
||||||
|
The goal is to generate typescript code from golang using AST.
|
||||||
|
So you can use intellisense in the development IDE.
|
||||||
|
|
||||||
|
## 
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
[Golang types traslation](docs/TsGoTypes.md)
|
||||||
|
|
||||||
|
[Typescript: TSDeclaration](docs/TsDeclaration.md)
|
||||||
|
|
||||||
|
[Typescript: TStype](docs/TsType.md)
|
||||||
|
|
||||||
|
[Typescript: interface](docs/TsInterface.md)
|
||||||
|
[Struct tags](docs/TsTags.md)
|
||||||
|
|
||||||
|
[Typescript: TsEndpoint](docs/TsEndpoint.md)
|
||||||
|
|
||||||
|
[Typescript: const](docs/TsConst.md)
|
||||||
|
|
||||||
|
[Typescript: enum](docs/TsEnum.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### Server Examle
|
||||||
|
|
||||||
|
[server examle](docs/TsExportEndpoints.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### Can I use it/contribute?
|
||||||
|
|
||||||
|
Sure, but you should probably start your own from scratch. I built this in about one week and it was an interesting experience, I recommend you do the same. My goal was never to make good or reusable code, so it's neither good nor reusable. If you do decide to work on such a system, I would suggest adding the following:
|
||||||
|
|
||||||
|
- Talk about ghost bridge over all the world
|
||||||
|
- Suggest some ideas
|
||||||
|
- Develop good reusable code
|
||||||
|
- Add tests, comments and GoDoc
|
||||||
|
- Be Happy
|
||||||
|
|
||||||
|
#### Alright then...
|
||||||
|
|
||||||
|
Cool. I'm on linkedin Golang nuts group https://www.linkedin.com/groups/3712244/
|
||||||
|
My linkedin page: https://www.linkedin.com/in/fabio-prada-a9159b75/
|
||||||
|
Discord channel #tsrpc: https://discord.com/channels/1046004205556617237/1046004333734531092
|
||||||
|
|
@ -0,0 +1,20 @@
|
||||||
|
#### Typescript: const
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Typescript: const
|
||||||
|
const Timeout = 1000
|
||||||
|
generate:
|
||||||
|
export const Timeout = 1000
|
||||||
|
|
||||||
|
// Typescript: const
|
||||||
|
const (
|
||||||
|
One string = "one"
|
||||||
|
Cento int = 100
|
||||||
|
)
|
||||||
|
generate:
|
||||||
|
export const One = "one"
|
||||||
|
export const Cento = 100
|
||||||
|
|
||||||
|
```
|
||||||
|
|
@ -0,0 +1,12 @@
|
||||||
|
#### Typescript: TSDeclaration
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Typescript: TSDeclaration= Nullable<T> = T | null;
|
||||||
|
// Typescript: TSDeclaration= Record<K extends string | number | symbol, T> = { [P in K]: T; }
|
||||||
|
// Typescript: TSDeclaration= MySecialArray<T> = T[];
|
||||||
|
generate: export type Nullable<T> = T | null;
|
||||||
|
export type Record<K extends string | number | symbol, T> = { [P in K]: T };
|
||||||
|
export type MySecialArray<T> = T[];
|
||||||
|
```
|
||||||
|
|
@ -0,0 +1,37 @@
|
||||||
|
#### Typescript: TSEndpoint
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
|
||||||
|
// Typescript: TSEndpoint= path=/ping; name=ping; method=GET; response=string
|
||||||
|
r.GET("/ping", func(c *gin.Context) {
|
||||||
|
response := HTTPResponse{Data: "pong", Error: nil}
|
||||||
|
c.JSON(http.StatusOK, response)
|
||||||
|
})
|
||||||
|
generate:
|
||||||
|
// Typescript: TSEndpoint= path=/ping; name=ping; method=GET; response=string
|
||||||
|
// server/server.go Line: 53
|
||||||
|
export const ping = async ():Promise<{ data:string; error: Nullable<string> }> => {
|
||||||
|
return await api.GET("/ping") as { data: string; error: Nullable<string> };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Typescript: TSEndpoint= path=/postTest; name=postTest; method=POST; request=FormRequest; response=FormResponse
|
||||||
|
r.POST("/postTest", func(c *gin.Context) {
|
||||||
|
var requestBody FormRequest
|
||||||
|
if err := c.BindJSON(&requestBody); err != nil {
|
||||||
|
response := HTTPResponse{Data: nil, Error: "wrongData"}
|
||||||
|
c.JSON(http.StatusOK, response)
|
||||||
|
}
|
||||||
|
response := HTTPResponse{Data: FormResponse{Test: fmt.Sprintf("%d", requestBody.Count)}, Error: nil}
|
||||||
|
c.JSON(http.StatusOK, response)
|
||||||
|
})
|
||||||
|
|
||||||
|
generate:
|
||||||
|
|
||||||
|
// Typescript: TSEndpoint= path=/postTest; name=postTest; method=POST; request=FormRequest; response=FormResponse
|
||||||
|
// server/server.go Line: 73
|
||||||
|
export const postTest = async (data: FormRequest):Promise<{ data:FormResponse; error: Nullable<string> }> => {
|
||||||
|
return await api.POST("/postTest", data) as { data: FormResponse; error: Nullable<string> };
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
@ -0,0 +1,58 @@
|
||||||
|
#### Typescript: enum
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
type Direction int
|
||||||
|
// Typescript: enum=Direction
|
||||||
|
const (
|
||||||
|
North Direction = iota
|
||||||
|
East
|
||||||
|
South
|
||||||
|
West
|
||||||
|
)
|
||||||
|
func (d Direction) String() string {
|
||||||
|
return [...]string{"North", "East", "South", "West"}[d]
|
||||||
|
}
|
||||||
|
generate:
|
||||||
|
export const EnumDirection = {
|
||||||
|
North: 0,
|
||||||
|
East: 1,
|
||||||
|
South: 2,
|
||||||
|
West: 3,
|
||||||
|
} as const
|
||||||
|
export type Direction = typeof EnumDirection[keyof typeof EnumDirection]
|
||||||
|
|
||||||
|
type Season string
|
||||||
|
// Typescript: enum=Season
|
||||||
|
const (
|
||||||
|
Summer Season = "summer"
|
||||||
|
Autumn = "autumn"
|
||||||
|
Winter = "winter"
|
||||||
|
Spring = "spring"
|
||||||
|
)
|
||||||
|
generate:
|
||||||
|
export const EnumSeason = {
|
||||||
|
Summer: "summer",
|
||||||
|
Autumn: "autumn",
|
||||||
|
Winter: "winter",
|
||||||
|
Spring: "spring",
|
||||||
|
} as const
|
||||||
|
export type Season = typeof EnumSeason[keyof typeof EnumSeason]
|
||||||
|
|
||||||
|
// Typescript: enum=Test
|
||||||
|
const (
|
||||||
|
A int = iota
|
||||||
|
B
|
||||||
|
C
|
||||||
|
D
|
||||||
|
)
|
||||||
|
generate:
|
||||||
|
export const EnumTest = {
|
||||||
|
A: 0,
|
||||||
|
B: 1,
|
||||||
|
C: 2,
|
||||||
|
D: 3,
|
||||||
|
}
|
||||||
|
export type Test = typeof EnumTest[keyof typeof EnumTest]
|
||||||
|
```
|
||||||
|
|
@ -0,0 +1,80 @@
|
||||||
|
### Example of endpoint exportation
|
||||||
|
|
||||||
|
golang declaration
|
||||||
|
|
||||||
|
```golang
|
||||||
|
// Typescript: TSDeclaration= Nullable<T> = T | null;
|
||||||
|
// Typescript: TSDeclaration= Record<K extends string | number | symbol, T> = { [P in K]: T; }
|
||||||
|
|
||||||
|
// Typescript: interface
|
||||||
|
type HTTPResponse struct {
|
||||||
|
Data interface{} `json:"data"`
|
||||||
|
Error interface{} `json:"error"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Typescript: interface
|
||||||
|
type FormRequest struct {
|
||||||
|
Req string `json:"req"`
|
||||||
|
Count int `json:"count"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Typescript: interface
|
||||||
|
type FormResponse struct {
|
||||||
|
Test string `json:"test"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Typescript: TSEndpoint= path=/postTest; name=postTest; method=POST; request=FormRequest; response=FormResponse
|
||||||
|
r.POST("/postTest", func(c *gin.Context) {
|
||||||
|
var requestBody FormRequest
|
||||||
|
if err := c.BindJSON(&requestBody); err != nil {
|
||||||
|
response := HTTPResponse{Data: nil, Error: "wrongData"}
|
||||||
|
c.JSON(http.StatusOK, response)
|
||||||
|
}
|
||||||
|
response := HTTPResponse{Data: FormResponse{Test: fmt.Sprintf("%d", requestBody.Count)}, Error: nil}
|
||||||
|
c.JSON(http.StatusOK, response)
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
generated code
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
//
|
||||||
|
// namespace server
|
||||||
|
//
|
||||||
|
|
||||||
|
export namespace server {
|
||||||
|
export interface FormRequest {
|
||||||
|
req: string;
|
||||||
|
count: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FormResponse {
|
||||||
|
test: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HTTPResponse {
|
||||||
|
data: unknown;
|
||||||
|
error: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Typescript: TSEndpoint= path=/postTest; name=postTest; method=POST; request=FormRequest; response=FormResponse
|
||||||
|
// server/server.go Line: 73
|
||||||
|
export const postTest = async (data: FormRequest): Promise<{ data: FormResponse; error: Nullable<string> }> => {
|
||||||
|
return (await api.POST("/postTest", data)) as { data: FormResponse; error: Nullable<string> };
|
||||||
|
};
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
How to use in frontend
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const input = <server.FormRequest>{ req: "some request", count: 456 };
|
||||||
|
const { data, error } = await server.postTest(input);
|
||||||
|
if (!error) {
|
||||||
|
console.log(data);
|
||||||
|
result = data.test;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
exported code template
|
||||||
|
[fetch template](./TsFetchTemplate.md)
|
||||||
|
|
@ -0,0 +1,429 @@
|
||||||
|
# ts-rpc
|
||||||
|
|
||||||
|
#### typescript fetch template
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
//
|
||||||
|
// {{.CreatedOn.Format "Jan 02, 2006 15:04:05 UTC" }}
|
||||||
|
//
|
||||||
|
|
||||||
|
export interface ApiRestResponse {
|
||||||
|
data?: unknown;
|
||||||
|
error: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Api {
|
||||||
|
apiUrl: string;
|
||||||
|
localStorage: Storage | null;
|
||||||
|
|
||||||
|
constructor(apiurl: string) {
|
||||||
|
this.apiUrl = apiurl;
|
||||||
|
this.localStorage = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
request(method: string, url: string, data: unknown, timeout = 7000, upload = false) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
let auth: string;
|
||||||
|
const headers: { [key: string]: string } = {
|
||||||
|
"Content-Type": upload ? "multipart/form-data" : "application/json",
|
||||||
|
"Cache-Control": "no-cache",
|
||||||
|
};
|
||||||
|
if (this.localStorage) {
|
||||||
|
auth = localStorage.getItem("jwt-token") as string;
|
||||||
|
headers["Auth-Token"] = auth;
|
||||||
|
}
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
||||||
|
|
||||||
|
let requestOptions: RequestInit = {
|
||||||
|
method: method,
|
||||||
|
body: data ? JSON.stringify(data) : undefined,
|
||||||
|
cache: "no-store",
|
||||||
|
mode: "cors",
|
||||||
|
credentials: "include",
|
||||||
|
headers: headers || {},
|
||||||
|
signal: controller.signal,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (upload) {
|
||||||
|
requestOptions = {
|
||||||
|
method: method,
|
||||||
|
body: data as FormData,
|
||||||
|
signal: controller.signal,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
fetch(url, requestOptions)
|
||||||
|
.then((response) => {
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = `api.error.${response.statusText}`;
|
||||||
|
throw error;
|
||||||
|
} else {
|
||||||
|
if (this.localStorage) {
|
||||||
|
const jwt = response.headers.get("Auth-Token");
|
||||||
|
if (jwt) {
|
||||||
|
this.localStorage.setItem("jwt-token", jwt);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return response.json() as Promise<ApiRestResponse>;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.then((data) => {
|
||||||
|
clearTimeout(timeoutId);
|
||||||
|
if (typeof data === "object" && data.hasOwnProperty("data") && data.hasOwnProperty("error")) {
|
||||||
|
const d: ApiRestResponse = data;
|
||||||
|
if (d.error) {
|
||||||
|
throw d.error;
|
||||||
|
} else {
|
||||||
|
resolve(d);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw "api.error.wrongdatatype";
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
clearTimeout(timeoutId);
|
||||||
|
if ((error as Error).toString() === "DOMException: The user aborted a request.") {
|
||||||
|
reject(new Error("api.error.timeouterror"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ((error as Error).toString() === "TypeError: Failed to fetch") {
|
||||||
|
reject(new Error("api.error.connectionerror"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
reject(error);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
processResult(url: string, result: ApiRestResponse): { data: unknown; error: string | null } {
|
||||||
|
if (typeof result.data !== "object") {
|
||||||
|
return { data: result.data, error: null };
|
||||||
|
} else if (!result.data) {
|
||||||
|
result.data = {};
|
||||||
|
}
|
||||||
|
return { data: result.data, error: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
processError(
|
||||||
|
error: Error,
|
||||||
|
url: string
|
||||||
|
): {
|
||||||
|
data: unknown;
|
||||||
|
error: string | null;
|
||||||
|
} {
|
||||||
|
if (error.message === "api.error.timeouterror") {
|
||||||
|
Object.defineProperty(error, "__api_error__", {
|
||||||
|
value: error.message,
|
||||||
|
writable: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { data: null, error: error.message };
|
||||||
|
}
|
||||||
|
if (error.message === "api.error.connectionerror") {
|
||||||
|
Object.defineProperty(error, "__api_error__", {
|
||||||
|
value: error.message,
|
||||||
|
writable: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { data: null, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
data: null,
|
||||||
|
error: error.message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async POST(
|
||||||
|
url: string,
|
||||||
|
|
||||||
|
data: unknown,
|
||||||
|
timeout?: number
|
||||||
|
): Promise<{
|
||||||
|
data: unknown;
|
||||||
|
error: string | null;
|
||||||
|
}> {
|
||||||
|
try {
|
||||||
|
let upload = false;
|
||||||
|
if (url.includes("/upload/")) {
|
||||||
|
upload = true;
|
||||||
|
}
|
||||||
|
const result = (await this.request("POST", `${this.apiUrl}${url}`, data, timeout, upload)) as ApiRestResponse;
|
||||||
|
return this.processResult(url, result);
|
||||||
|
} catch (error) {
|
||||||
|
return new Promise<{
|
||||||
|
data: unknown;
|
||||||
|
error: string | null;
|
||||||
|
}>(async (resolve) => {
|
||||||
|
let result = this.processError(error, `POST => ${this.apiUrl}${url}`);
|
||||||
|
resolve(result);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async GET(
|
||||||
|
url: string,
|
||||||
|
timeout?: number
|
||||||
|
): Promise<{
|
||||||
|
data: unknown;
|
||||||
|
error: string | null;
|
||||||
|
}> {
|
||||||
|
try {
|
||||||
|
const result = (await this.request("GET", `${this.apiUrl}${url}`, null, timeout)) as ApiRestResponse;
|
||||||
|
return this.processResult(url, result);
|
||||||
|
} catch (error) {
|
||||||
|
return new Promise<{
|
||||||
|
data: unknown;
|
||||||
|
error: string | null;
|
||||||
|
}>(async (resolve) => {
|
||||||
|
let result = this.processError(error, `GET => ${this.apiUrl}${url}`);
|
||||||
|
resolve(result);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async UPLOAD(
|
||||||
|
url: string,
|
||||||
|
data: unknown,
|
||||||
|
timeout?: number
|
||||||
|
): Promise<{
|
||||||
|
data: unknown;
|
||||||
|
error: string | null;
|
||||||
|
}> {
|
||||||
|
try {
|
||||||
|
const result = (await this.request("POST", `${this.apiUrl}${url}`, data, timeout, true)) as ApiRestResponse;
|
||||||
|
return this.processResult(url, result);
|
||||||
|
} catch (error) {
|
||||||
|
return new Promise<{
|
||||||
|
data: unknown;
|
||||||
|
error: string | null;
|
||||||
|
}>((resolve) => {
|
||||||
|
resolve(this.processError(error, `POST => ${this.apiUrl}${url}`));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const api = new Api("{{ .Url}}");
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### Golang template as constant
|
||||||
|
|
||||||
|
_note_: incuded in source code
|
||||||
|
_note_: replce \` (backtick) inside \` (backtick) with \` + "\`" + \`
|
||||||
|
|
||||||
|
```golang
|
||||||
|
package tsrpc
|
||||||
|
|
||||||
|
const TsApiTemplate = `
|
||||||
|
//
|
||||||
|
// {{.CreatedOn.Format "Jan 02, 2006 15:04:05 UTC" }}
|
||||||
|
//
|
||||||
|
|
||||||
|
export interface ApiRestResponse {
|
||||||
|
data?: unknown;
|
||||||
|
error: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Api {
|
||||||
|
apiUrl: string;
|
||||||
|
localStorage: Storage | null;
|
||||||
|
|
||||||
|
constructor(apiurl: string) {
|
||||||
|
this.apiUrl = apiurl;
|
||||||
|
this.localStorage = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
request(method: string, url: string, data: unknown, timeout = 7000, upload = false) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
let auth: string;
|
||||||
|
const headers: { [key: string]: string } = {
|
||||||
|
"Content-Type": upload ? "multipart/form-data" : "application/json",
|
||||||
|
"Cache-Control": "no-cache",
|
||||||
|
};
|
||||||
|
if (this.localStorage) {
|
||||||
|
auth = localStorage.getItem("jwt-token") as string;
|
||||||
|
headers["Auth-Token"] = auth;
|
||||||
|
}
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
||||||
|
|
||||||
|
let requestOptions: RequestInit = {
|
||||||
|
method: method,
|
||||||
|
body: data ? JSON.stringify(data) : undefined,
|
||||||
|
cache: "no-store",
|
||||||
|
mode: "cors",
|
||||||
|
credentials: "include",
|
||||||
|
headers: headers || {},
|
||||||
|
signal: controller.signal,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (upload) {
|
||||||
|
requestOptions = {
|
||||||
|
method: method,
|
||||||
|
body: data as FormData,
|
||||||
|
signal: controller.signal,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
fetch(url, requestOptions)
|
||||||
|
.then((response) => {
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = ` + "`" + `api.error.${response.statusText}` + "`" + `;
|
||||||
|
throw error;
|
||||||
|
} else {
|
||||||
|
if (this.localStorage) {
|
||||||
|
const jwt = response.headers.get("Auth-Token");
|
||||||
|
if (jwt) {
|
||||||
|
this.localStorage.setItem("jwt-token", jwt);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return response.json() as Promise<ApiRestResponse>;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.then((data) => {
|
||||||
|
clearTimeout(timeoutId);
|
||||||
|
if (typeof data === "object" && data.hasOwnProperty("data") && data.hasOwnProperty("error")) {
|
||||||
|
const d: ApiRestResponse = data;
|
||||||
|
if (d.error) {
|
||||||
|
throw d.error;
|
||||||
|
} else {
|
||||||
|
resolve(d);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw "api.error.wrongdatatype";
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
clearTimeout(timeoutId);
|
||||||
|
if ((error as Error).toString() === "DOMException: The user aborted a request.") {
|
||||||
|
reject(new Error("api.error.timeouterror"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ((error as Error).toString() === "TypeError: Failed to fetch") {
|
||||||
|
reject(new Error("api.error.connectionerror"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
reject(error);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
processResult(url: string, result: ApiRestResponse): { data: unknown; error: string | null } {
|
||||||
|
if (typeof result.data !== "object") {
|
||||||
|
return { data: result.data, error: null };
|
||||||
|
} else if (!result.data) {
|
||||||
|
result.data = {};
|
||||||
|
}
|
||||||
|
return { data: result.data, error: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
processError(
|
||||||
|
error: Error,
|
||||||
|
url: string
|
||||||
|
): {
|
||||||
|
data: unknown;
|
||||||
|
error: string | null;
|
||||||
|
} {
|
||||||
|
if (error.message === "api.error.timeouterror") {
|
||||||
|
Object.defineProperty(error, "__api_error__", {
|
||||||
|
value: error.message,
|
||||||
|
writable: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { data: null, error: error.message };
|
||||||
|
}
|
||||||
|
if (error.message === "api.error.connectionerror") {
|
||||||
|
Object.defineProperty(error, "__api_error__", {
|
||||||
|
value: error.message,
|
||||||
|
writable: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { data: null, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
data: null,
|
||||||
|
error: error.message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async POST(
|
||||||
|
url: string,
|
||||||
|
|
||||||
|
data: unknown,
|
||||||
|
timeout?: number
|
||||||
|
): Promise<{
|
||||||
|
data: unknown;
|
||||||
|
error: string | null;
|
||||||
|
}> {
|
||||||
|
try {
|
||||||
|
let upload = false;
|
||||||
|
if (url.includes("/upload/")) {
|
||||||
|
upload = true;
|
||||||
|
}
|
||||||
|
const result = (await this.request("POST", ` + "`" + `${this.apiUrl}${url}` + "`" + `, data, timeout, upload)) as ApiRestResponse;
|
||||||
|
return this.processResult(url, result);
|
||||||
|
} catch (error) {
|
||||||
|
return new Promise<{
|
||||||
|
data: unknown;
|
||||||
|
error: string | null;
|
||||||
|
}>(async (resolve) => {
|
||||||
|
let result = this.processError(error, ` + "`" + `POST => ${this.apiUrl}${url}` + "`" + `);
|
||||||
|
resolve(result);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async GET(
|
||||||
|
url: string,
|
||||||
|
timeout?: number
|
||||||
|
): Promise<{
|
||||||
|
data: unknown;
|
||||||
|
error: string | null;
|
||||||
|
}> {
|
||||||
|
try {
|
||||||
|
const result = (await this.request("GET", ` + "`" + `${this.apiUrl}${url}` + "`" + `, null, timeout)) as ApiRestResponse;
|
||||||
|
return this.processResult(url, result);
|
||||||
|
} catch (error) {
|
||||||
|
return new Promise<{
|
||||||
|
data: unknown;
|
||||||
|
error: string | null;
|
||||||
|
}>(async (resolve) => {
|
||||||
|
let result = this.processError(error, ` + "`" + `GET => ${this.apiUrl}${url}` + "`" + `);
|
||||||
|
resolve(result);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async UPLOAD(
|
||||||
|
url: string,
|
||||||
|
data: unknown,
|
||||||
|
timeout?: number
|
||||||
|
): Promise<{
|
||||||
|
data: unknown;
|
||||||
|
error: string | null;
|
||||||
|
}> {
|
||||||
|
try {
|
||||||
|
const result = (await this.request("POST", ` + "`" + `${this.apiUrl}${url}` + "`" + `, data, timeout, true)) as ApiRestResponse;
|
||||||
|
return this.processResult(url, result);
|
||||||
|
} catch (error) {
|
||||||
|
return new Promise<{
|
||||||
|
data: unknown;
|
||||||
|
error: string | null;
|
||||||
|
}>((resolve) => {
|
||||||
|
resolve(this.processError(error, ` + "`" + `POST => ${this.apiUrl}${url}` + "`" + `));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const api = new Api("{{ .Url}}");
|
||||||
|
`
|
||||||
|
|
||||||
|
```
|
||||||
|
|
@ -0,0 +1,30 @@
|
||||||
|
#### golang types traslation:
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
typescript number:
|
||||||
|
|
||||||
|
- uint8
|
||||||
|
- uint16
|
||||||
|
- uint32
|
||||||
|
- uint64
|
||||||
|
- uint
|
||||||
|
- int8
|
||||||
|
- int16
|
||||||
|
- int32
|
||||||
|
- int64
|
||||||
|
- int
|
||||||
|
- float32
|
||||||
|
- float64
|
||||||
|
|
||||||
|
typescript boolean:
|
||||||
|
|
||||||
|
- bool
|
||||||
|
|
||||||
|
typescript string:
|
||||||
|
|
||||||
|
- string
|
||||||
|
|
||||||
|
typescript unknown:
|
||||||
|
|
||||||
|
- interface{}
|
||||||
|
|
@ -0,0 +1,65 @@
|
||||||
|
#### Typescript: interface
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Typescript: interface
|
||||||
|
type HTTPResponse struct {
|
||||||
|
Data interface{} `json:"data"`
|
||||||
|
Error interface{} `json:"error"`
|
||||||
|
}
|
||||||
|
generate:
|
||||||
|
export interface HTTPResponse {
|
||||||
|
data: unknown;
|
||||||
|
error: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Typescript: interface
|
||||||
|
type FormRequest struct {
|
||||||
|
Req string `json:"req"`
|
||||||
|
Count int `json:"count"`
|
||||||
|
}
|
||||||
|
generate:
|
||||||
|
export interface FormRequest {
|
||||||
|
req: string;
|
||||||
|
count: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Typescript: interface
|
||||||
|
type FormResponse struct {
|
||||||
|
Test string `json:"test"`
|
||||||
|
}
|
||||||
|
generate:
|
||||||
|
export interface FormResponse {
|
||||||
|
test: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Typescript: interface
|
||||||
|
type FormResponse2 struct {
|
||||||
|
Test string `json:"test"`
|
||||||
|
User string `json:"user,omitempty"`
|
||||||
|
}
|
||||||
|
generate:
|
||||||
|
export interface FormResponse2 {
|
||||||
|
test: string;
|
||||||
|
user?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Typescript: interface
|
||||||
|
type FormResponse3 struct {
|
||||||
|
FormRequest `ts:"expand"`
|
||||||
|
Test string `json:"test"`
|
||||||
|
User string `json:"user,omitempty"`
|
||||||
|
Time time.Time `json:"time" ts:"type=Date"`
|
||||||
|
}
|
||||||
|
generate:
|
||||||
|
export interface FormResponse3 {
|
||||||
|
req: string;
|
||||||
|
count: number;
|
||||||
|
test: string;
|
||||||
|
user?: string;
|
||||||
|
time: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
```
|
||||||
|
|
@ -0,0 +1,14 @@
|
||||||
|
#### Struct field tags
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
|
||||||
|
tag `json:"fieldName"` this tag is manatory
|
||||||
|
tag `json:"-"` the field is not exported
|
||||||
|
tag `json:"fieldName,omitempty"` generate fieldName?: ("the props can be undefined")
|
||||||
|
|
||||||
|
tag `ts:"expand"` generate the golang composition in the interface
|
||||||
|
tag `ts:"type=Date"` force to use the type Date
|
||||||
|
tag `ts:"type=WhatEverYouWant"` force to use the type WhatEverYouWant
|
||||||
|
```
|
||||||
|
|
@ -0,0 +1,32 @@
|
||||||
|
#### Typescript: TStype
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Typescript: TStype= MyType = number
|
||||||
|
generate:
|
||||||
|
export type MyType = number
|
||||||
|
|
||||||
|
// examples
|
||||||
|
// Typescript: type
|
||||||
|
type TestType []int
|
||||||
|
generate:
|
||||||
|
export type TestType = number[]
|
||||||
|
|
||||||
|
|
||||||
|
// Typescript: type
|
||||||
|
type TestTypeMap map[string]map[int]string
|
||||||
|
generate:
|
||||||
|
export type TestTypeMap = Record<string, <Record<number, string>>>
|
||||||
|
|
||||||
|
|
||||||
|
// Typescript: type=Date
|
||||||
|
type TestTypeTime time.Time
|
||||||
|
generate:
|
||||||
|
export type TestTypeTime = Date
|
||||||
|
|
||||||
|
// typescript: type
|
||||||
|
type TestNullable *string
|
||||||
|
generate:
|
||||||
|
export type TestNullable = Nullable<string>
|
||||||
|
```
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 145 KiB |
|
|
@ -0,0 +1,219 @@
|
||||||
|
// exportable typescript generated from golang
|
||||||
|
// Copyright (C) 2022 Fabio Prada
|
||||||
|
|
||||||
|
package tsrpc
|
||||||
|
|
||||||
|
const TsApiTemplate = `
|
||||||
|
//
|
||||||
|
// Typescript API generated from gofiber backend
|
||||||
|
// Copyright (C) 2022 - 2025 Fabio Prada
|
||||||
|
//
|
||||||
|
// This file was generated by github.com/millevolte/ts-rpc
|
||||||
|
//
|
||||||
|
// {{.CreatedOn.Format "Jan 02, 2006 15:04:05 UTC" }}
|
||||||
|
//
|
||||||
|
|
||||||
|
export interface ApiRestResponse {
|
||||||
|
data?: unknown;
|
||||||
|
error: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isApiRestResponse(data: unknown): data is ApiRestResponse {
|
||||||
|
return (
|
||||||
|
typeof data === 'object' &&
|
||||||
|
data !== null &&
|
||||||
|
Object.prototype.hasOwnProperty.call(data, 'data') &&
|
||||||
|
Object.prototype.hasOwnProperty.call(data, 'error')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeError(error: unknown): Error {
|
||||||
|
if (error instanceof DOMException && error.name === 'AbortError') {
|
||||||
|
return new Error('api.error.timeouterror');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error instanceof TypeError && error.message === 'Failed to fetch') {
|
||||||
|
return new Error('api.error.connectionerror');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error instanceof Error) {
|
||||||
|
return error;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Error(String(error));
|
||||||
|
}
|
||||||
|
|
||||||
|
export default class Api {
|
||||||
|
apiUrl: string;
|
||||||
|
localStorage: Storage | null;
|
||||||
|
|
||||||
|
constructor(apiurl: string) {
|
||||||
|
this.apiUrl = apiurl;
|
||||||
|
this.localStorage = window.localStorage;
|
||||||
|
}
|
||||||
|
|
||||||
|
async request(
|
||||||
|
method: string,
|
||||||
|
url: string,
|
||||||
|
data: unknown,
|
||||||
|
timeout = 7000,
|
||||||
|
upload = false,
|
||||||
|
): Promise<ApiRestResponse> {
|
||||||
|
const headers: { [key: string]: string } = {
|
||||||
|
'Cache-Control': 'no-cache',
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!upload) {
|
||||||
|
headers['Content-Type'] = 'application/json';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.localStorage) {
|
||||||
|
const auth = this.localStorage.getItem('Auth-Token');
|
||||||
|
if (auth) {
|
||||||
|
headers['Auth-Token'] = auth;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
||||||
|
const requestOptions: RequestInit = {
|
||||||
|
method,
|
||||||
|
cache: 'no-store',
|
||||||
|
mode: 'cors',
|
||||||
|
credentials: 'include',
|
||||||
|
headers,
|
||||||
|
signal: controller.signal,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (upload) {
|
||||||
|
requestOptions.body = data as FormData;
|
||||||
|
} else if (data !== null && data !== undefined) {
|
||||||
|
requestOptions.body = JSON.stringify(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(url, requestOptions);
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('api.error.' + response.statusText);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.localStorage) {
|
||||||
|
const jwt = response.headers.get('Auth-Token');
|
||||||
|
if (jwt) {
|
||||||
|
this.localStorage.setItem('Auth-Token', jwt);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const responseData = (await response.json()) as unknown;
|
||||||
|
if (!isApiRestResponse(responseData)) {
|
||||||
|
throw new Error('api.error.wrongdatatype');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (responseData.error) {
|
||||||
|
throw new Error(responseData.error);
|
||||||
|
}
|
||||||
|
|
||||||
|
return responseData;
|
||||||
|
} catch (error: unknown) {
|
||||||
|
throw normalizeError(error);
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timeoutId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
processResult(result: ApiRestResponse): { data: unknown; error: string | null } {
|
||||||
|
if (typeof result.data !== 'object') {
|
||||||
|
return { data: result.data, error: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!result.data) {
|
||||||
|
result.data = {};
|
||||||
|
}
|
||||||
|
|
||||||
|
return { data: result.data, error: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
processError(error: unknown): {
|
||||||
|
data: unknown;
|
||||||
|
error: string | null;
|
||||||
|
} {
|
||||||
|
const normalizedError = normalizeError(error);
|
||||||
|
|
||||||
|
if (normalizedError.message === 'api.error.timeouterror') {
|
||||||
|
Object.defineProperty(normalizedError, '__api_error__', {
|
||||||
|
value: normalizedError.message,
|
||||||
|
writable: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { data: null, error: normalizedError.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (normalizedError.message === 'api.error.connectionerror') {
|
||||||
|
Object.defineProperty(normalizedError, '__api_error__', {
|
||||||
|
value: normalizedError.message,
|
||||||
|
writable: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { data: null, error: normalizedError.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
data: null,
|
||||||
|
error: normalizedError.message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async POST(
|
||||||
|
url: string,
|
||||||
|
data: unknown,
|
||||||
|
timeout?: number,
|
||||||
|
): Promise<{
|
||||||
|
data: unknown;
|
||||||
|
error: string | null;
|
||||||
|
}> {
|
||||||
|
try {
|
||||||
|
const upload = url.includes('/upload/');
|
||||||
|
const result = await this.request('POST', this.apiUrl + url, data, timeout, upload);
|
||||||
|
|
||||||
|
return this.processResult(result);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
return this.processError(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async GET(
|
||||||
|
url: string,
|
||||||
|
timeout?: number,
|
||||||
|
): Promise<{
|
||||||
|
data: unknown;
|
||||||
|
error: string | null;
|
||||||
|
}> {
|
||||||
|
try {
|
||||||
|
const result = await this.request('GET', this.apiUrl + url, null, timeout);
|
||||||
|
return this.processResult(result);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
return this.processError(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async UPLOAD(
|
||||||
|
url: string,
|
||||||
|
data: unknown,
|
||||||
|
timeout?: number,
|
||||||
|
): Promise<{
|
||||||
|
data: unknown;
|
||||||
|
error: string | null;
|
||||||
|
}> {
|
||||||
|
try {
|
||||||
|
const result = await this.request('POST', this.apiUrl + url, data, timeout, true);
|
||||||
|
|
||||||
|
return this.processResult(result);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
return this.processError(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const api = new Api('{{ .APIURL }}');
|
||||||
|
`
|
||||||
|
|
@ -0,0 +1,200 @@
|
||||||
|
// exportable typescript generated from golang
|
||||||
|
// Copyright (C) 2022 Fabio Prada
|
||||||
|
|
||||||
|
package tsrpc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"text/template"
|
||||||
|
)
|
||||||
|
|
||||||
|
type TSEndpoint struct {
|
||||||
|
Name string
|
||||||
|
Path string
|
||||||
|
Method string
|
||||||
|
Request string
|
||||||
|
Response string
|
||||||
|
RequestTs string
|
||||||
|
ResponseTs string
|
||||||
|
Source string
|
||||||
|
File string
|
||||||
|
Line int
|
||||||
|
}
|
||||||
|
|
||||||
|
func ParseEndpoint(source string, file string, line int) TSEndpoint {
|
||||||
|
p := strings.Index(source, "TSEndpoint=")
|
||||||
|
s := strings.Trim(source[p+len("TSEndpoint="):], " ")
|
||||||
|
a := strings.Split(s, ";")
|
||||||
|
n := 0
|
||||||
|
endpoint := TSEndpoint{}
|
||||||
|
endpoint.Source = strings.Trim(source, "\t")
|
||||||
|
endpoint.File = file
|
||||||
|
endpoint.Line = line
|
||||||
|
|
||||||
|
for _, v := range a {
|
||||||
|
t := strings.Split(v, "=")
|
||||||
|
if len(t) < 2 || strings.Trim(t[1], " ") == "" {
|
||||||
|
exitOnError(fmt.Errorf("worong endpoint: %s", s))
|
||||||
|
}
|
||||||
|
if len(t) == 2 {
|
||||||
|
switch strings.Trim(t[0], " ") {
|
||||||
|
case "path":
|
||||||
|
n++
|
||||||
|
endpoint.Path = strings.Trim(t[1], " ")
|
||||||
|
case "method":
|
||||||
|
n++
|
||||||
|
endpoint.Method = strings.Trim(t[1], " ")
|
||||||
|
case "name":
|
||||||
|
n++
|
||||||
|
endpoint.Name = strings.Trim(t[1], " ")
|
||||||
|
case "request":
|
||||||
|
n++
|
||||||
|
endpoint.Request = strings.Trim(t[1], " ")
|
||||||
|
case "response":
|
||||||
|
n++
|
||||||
|
endpoint.Response = strings.Trim(t[1], " ")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
exitOnError(fmt.Errorf("wrong endpoint props: %s", s))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if endpoint.Method != "POST" && endpoint.Method != "GET" {
|
||||||
|
exitOnError(fmt.Errorf("wrong endpoint method: %s", s))
|
||||||
|
}
|
||||||
|
|
||||||
|
if endpoint.Method == "GET" && n < 4 {
|
||||||
|
exitOnError(fmt.Errorf("wrong endpoint number of props: %s", s))
|
||||||
|
}
|
||||||
|
if endpoint.Method == "POST" && n < 5 {
|
||||||
|
exitOnError(fmt.Errorf("wrong endpoint number of props: %s", s))
|
||||||
|
}
|
||||||
|
|
||||||
|
return endpoint
|
||||||
|
}
|
||||||
|
|
||||||
|
type tplData struct {
|
||||||
|
E *TSEndpoint
|
||||||
|
Path string
|
||||||
|
Params []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *TSEndpoint) VerifyTypes(info TSInfo, p string) {
|
||||||
|
a := strings.Split(e.Request, ".")
|
||||||
|
if e.Request != "" {
|
||||||
|
if len(a) == 2 {
|
||||||
|
e.RequestTs = a[1]
|
||||||
|
if strings.HasPrefix(a[1], "[]") {
|
||||||
|
a[1] = strings.TrimPrefix(a[1], "[]")
|
||||||
|
e.RequestTs = fmt.Sprintf("%s[]", a[1])
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(a[1], "*") {
|
||||||
|
a[1] = strings.TrimPrefix(a[1], "*")
|
||||||
|
e.RequestTs = fmt.Sprintf("Nullable<%s>", a[1])
|
||||||
|
}
|
||||||
|
e.Request = fmt.Sprintf("%s.%s", a[0], a[1])
|
||||||
|
if !info.find(a[0], a[1]) {
|
||||||
|
exitOnError(fmt.Errorf("endpoint request not found: %s AT %s Line: %d ", e.Request, e.File, e.Line))
|
||||||
|
}
|
||||||
|
info.setTypescript(a[0], a[1], true)
|
||||||
|
}
|
||||||
|
if len(a) == 1 {
|
||||||
|
e.RequestTs = a[0]
|
||||||
|
if strings.HasPrefix(a[0], "[]") {
|
||||||
|
a[0] = strings.TrimPrefix(a[0], "[]")
|
||||||
|
e.RequestTs = fmt.Sprintf("%s[]", a[0])
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(a[0], "*") {
|
||||||
|
a[0] = strings.TrimPrefix(a[0], "*")
|
||||||
|
e.RequestTs = fmt.Sprintf("Nullable<%s>", a[0])
|
||||||
|
}
|
||||||
|
e.Request = a[0]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
a = strings.Split(e.Response, ".")
|
||||||
|
if len(a) == 2 {
|
||||||
|
if !info.find(a[0], a[1]) {
|
||||||
|
exitOnError(fmt.Errorf("endpoint response not found: %s AT %s Line: %d ", e.Request, e.File, e.Line))
|
||||||
|
}
|
||||||
|
e.ResponseTs = a[1]
|
||||||
|
if strings.HasPrefix(a[1], "[]") {
|
||||||
|
a[1] = strings.TrimPrefix(a[1], "[]")
|
||||||
|
e.ResponseTs = fmt.Sprintf("%s[]", a[1])
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(a[1], "*") {
|
||||||
|
a[1] = strings.TrimPrefix(a[1], "*")
|
||||||
|
e.ResponseTs = fmt.Sprintf("Nullable<%s>", a[1])
|
||||||
|
}
|
||||||
|
e.Response = fmt.Sprintf("%s.%s", a[0], a[1])
|
||||||
|
}
|
||||||
|
if len(a) == 1 {
|
||||||
|
e.ResponseTs = a[0]
|
||||||
|
if strings.HasPrefix(a[0], "[]") {
|
||||||
|
a[0] = strings.TrimPrefix(a[0], "[]")
|
||||||
|
e.ResponseTs = fmt.Sprintf("%s[]", a[0])
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(a[0], "*") {
|
||||||
|
a[0] = strings.TrimPrefix(a[0], "*")
|
||||||
|
e.ResponseTs = fmt.Sprintf("Nullable<%s>", a[0])
|
||||||
|
}
|
||||||
|
e.Response = a[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *TSEndpoint) ToTs(pkg string) string {
|
||||||
|
data := tplData{E: e, Path: e.Path, Params: []string{}}
|
||||||
|
tpl := `
|
||||||
|
{{ .E.Source }}
|
||||||
|
// {{ .E.File }} Line: {{ .E.Line }}
|
||||||
|
{{if eq .E.Method "GET"}}export const {{ .E.Name}} = async ({{range $v := .Params}}{{$v}}{{end}}):Promise<{ data:{{.E.ResponseTs}}; error: Nullable<string> }> => {
|
||||||
|
return await api.GET({{ .Path}}) as { data: {{ .E.ResponseTs}}; error: Nullable<string> };
|
||||||
|
}{{end}}{{if eq .E.Method "POST"}}export const {{ .E.Name}} = async (data: {{ .E.RequestTs}}):Promise<{ data:{{.E.ResponseTs}}; error: Nullable<string> }> => {
|
||||||
|
return await api.POST("{{ .Path}}", data) as { data: {{ .E.ResponseTs}}; error: Nullable<string> };
|
||||||
|
}{{end}}`
|
||||||
|
|
||||||
|
if e.Method == "GET" {
|
||||||
|
a := strings.Split(e.Path, "/")
|
||||||
|
c := ""
|
||||||
|
f := false
|
||||||
|
for _, v := range a {
|
||||||
|
if len(v) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
prefix := v[0:1]
|
||||||
|
|
||||||
|
if f {
|
||||||
|
c = ", "
|
||||||
|
}
|
||||||
|
|
||||||
|
if prefix == ":" {
|
||||||
|
f = true
|
||||||
|
data.Params = append(data.Params, fmt.Sprintf("%s%s: string", c, v[1:]))
|
||||||
|
data.Path = strings.Replace(data.Path, v, fmt.Sprintf("${%s}", v[1:]), 1)
|
||||||
|
} else if prefix == "*" {
|
||||||
|
f = true
|
||||||
|
data.Params = append(data.Params, fmt.Sprintf("%s%s: Nullable<string>", c, v[1:]))
|
||||||
|
data.Path = strings.Replace(data.Path, v, fmt.Sprintf("${%s}", v[1:]), 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(data.Params) > 0 {
|
||||||
|
data.Path = fmt.Sprintf("`%s`", data.Path)
|
||||||
|
} else {
|
||||||
|
data.Path = fmt.Sprintf("\"%s\"", data.Path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
t, err := template.New("test").Parse(tpl)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
var result bytes.Buffer
|
||||||
|
err = t.Execute(&result, data)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.String()
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,14 @@
|
||||||
|
// exportable typescript generated from golang
|
||||||
|
// Copyright (C) 2022 Fabio Prada
|
||||||
|
|
||||||
|
package tsrpc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
|
func exitOnError(err error) {
|
||||||
|
fmt.Fprintf(os.Stderr, "error: %v\n", err)
|
||||||
|
//os.Exit(1)
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue