initial app
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
module.exports = {
|
||||
env: { browser: true, es2020: true },
|
||||
extends: [
|
||||
"eslint:recommended",
|
||||
"react-app",
|
||||
"airbnb-typescript",
|
||||
"airbnb/hooks",
|
||||
"plugin:@typescript-eslint/recommended",
|
||||
"plugin:react/recommended",
|
||||
"plugin:react-hooks/recommended",
|
||||
"prettier", // Help to cooperate ESLint and Prettier
|
||||
"plugin:prettier/recommended",
|
||||
],
|
||||
ignorePatterns: [
|
||||
"/build",
|
||||
"/dist",
|
||||
"/node_modules",
|
||||
"/.eslintrc.cjs",
|
||||
"/vite.config.ts",
|
||||
],
|
||||
parser: "@typescript-eslint/parser",
|
||||
parserOptions: {
|
||||
ecmaVersion: "latest",
|
||||
project: "./tsconfig.json",
|
||||
sourceType: "module",
|
||||
tsconfigRootDir: __dirname,
|
||||
},
|
||||
plugins: ["react-refresh"],
|
||||
rules: {
|
||||
// Run prettier separately but use its configuration
|
||||
// This speeds up on-the-fly linting during development
|
||||
"prettier/prettier": "off",
|
||||
"react-refresh/only-export-components": "warn",
|
||||
"import/no-extraneous-dependencies": [
|
||||
"error",
|
||||
{
|
||||
devDependencies: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
settings: {
|
||||
react: {
|
||||
version: "detect",
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
@@ -0,0 +1,9 @@
|
||||
/node_modules
|
||||
# Ignore artifacts:
|
||||
/build
|
||||
/dist
|
||||
/coverage
|
||||
|
||||
# generated code
|
||||
/src/api/naming
|
||||
/src/preview
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"importOrder": ["^[./]"],
|
||||
"importOrderSeparation": true
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Lukáš Čech</title>
|
||||
</head>
|
||||
<body>
|
||||
<script>
|
||||
window.global = window;
|
||||
try {
|
||||
window.APP_CONFIG = JSON.parse('{{ .Config }}');
|
||||
} catch (e) {
|
||||
console.debug('App uses development configuration');
|
||||
}
|
||||
</script>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+7288
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"name": "cv",
|
||||
"private": true,
|
||||
"version": "0.0.1",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "npm run check && tsc && vite build",
|
||||
"check": "npm run typecheck && echo \"Checking files with prettier\" && npm run prettier > /dev/null && npm run lint",
|
||||
"dev": "vite",
|
||||
"fix": "npm run prettier:format && npm run lint:fix",
|
||||
"lint": "eslint src --ext ts,tsx",
|
||||
"lint:fix": "eslint --fix src --ext ts,tsx",
|
||||
"lint:fix:changed": "eslint --fix $(npm run --silent list:changed)",
|
||||
"list:changed": "git diff HEAD --name-only --diff-filter=ACM --relative=app/console/src \"*.tsx\" \"*.ts\" \"*.js\" | sed 's#^#./src/#' ; git ls-files \"./src/*.tsx\" \"./src/*.ts\" -o --exclude-standard",
|
||||
"prettier": "prettier --config ./.prettierrc --check 'src/**/*.{js,ts,tsx}'",
|
||||
"prettier:format": "prettier --config ./.prettierrc --write 'src/**/*.{js,ts,tsx}'",
|
||||
"prettier:format:changed": "prettier --config ./.prettierrc --write $(npm run --silent list:changed)",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@emotion/react": "^11.11.0",
|
||||
"@emotion/styled": "^11.11.0",
|
||||
"@trivago/prettier-plugin-sort-imports": "^4.1.1",
|
||||
"@types/react": "^18.0.37",
|
||||
"@types/react-dom": "^18.0.11",
|
||||
"@typescript-eslint/eslint-plugin": "^5.59.0",
|
||||
"@typescript-eslint/parser": "^5.59.0",
|
||||
"@vitejs/plugin-react-swc": "^3.0.0",
|
||||
"eslint": "^8.38.0",
|
||||
"eslint-config-airbnb": "^19.0.4",
|
||||
"eslint-config-airbnb-typescript": "^17.0.0",
|
||||
"eslint-config-prettier": "^8.8.0",
|
||||
"eslint-config-react-app": "^7.0.1",
|
||||
"eslint-plugin-import": "^2.27.5",
|
||||
"eslint-plugin-prettier": "^4.2.1",
|
||||
"eslint-plugin-react-hooks": "^4.6.0",
|
||||
"eslint-plugin-react-refresh": "^0.3.4",
|
||||
"normalize.css": "^8.0.1",
|
||||
"react-intl": "^6.4.2",
|
||||
"react-router-dom": "^6.11.2",
|
||||
"typescript": "^5.0.2",
|
||||
"vite": "^4.3.9"
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.1 KiB |
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-terminal" width="250px" height="250px" viewBox="0 0 24 24" stroke-width="1.00" stroke="rgba(1, 1, 1, 1)" fill="none" stroke-linecap="round" stroke-linejoin="round"><circle cx="50%" cy="50%" r="50%" stroke="none" stroke-width="0" fill="rgba(255, 255, 255, 1)"/><g transform="translate(2.40, 2.40) scale(0.8)"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M5 7l5 5l-5 5"/><line x1="12" y1="19" x2="19" y2="19"/></g>
|
||||
|
||||
|
||||
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 519 B |
@@ -0,0 +1,17 @@
|
||||
import { Global } from "@emotion/react";
|
||||
import normalizeCss from "normalize.css/normalize.css?inline";
|
||||
import React from "react";
|
||||
import { IntlProvider } from "react-intl";
|
||||
|
||||
import Router from "./views/Router";
|
||||
|
||||
const App: React.FC = () => {
|
||||
return (
|
||||
<IntlProvider locale="en" defaultLocale="en">
|
||||
<Global styles={normalizeCss} />
|
||||
<Router />
|
||||
</IntlProvider>
|
||||
);
|
||||
};
|
||||
|
||||
export default App;
|
||||
@@ -0,0 +1,67 @@
|
||||
import React from "react";
|
||||
|
||||
type ErrorHandler = (error: Error, info: React.ErrorInfo) => void;
|
||||
type ErrorHandlingComponent<Props> = (
|
||||
props: Props,
|
||||
error?: Error
|
||||
) => React.ReactNode;
|
||||
|
||||
type ErrorState = { error?: Error };
|
||||
|
||||
function Catch<Props extends object>(
|
||||
component: ErrorHandlingComponent<Props>,
|
||||
errorHandler?: ErrorHandler
|
||||
): React.ComponentType<Props> {
|
||||
function Inner({ error, props }: { error?: Error; props: Props }) {
|
||||
return <React.Fragment>{component(props, error)}</React.Fragment>;
|
||||
}
|
||||
|
||||
return class CatchClass extends React.Component<Props, ErrorState> {
|
||||
state: ErrorState = {
|
||||
error: undefined,
|
||||
};
|
||||
|
||||
static getDerivedStateFromError(error: Error) {
|
||||
return { error };
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error, info: React.ErrorInfo) {
|
||||
if (errorHandler) {
|
||||
errorHandler(error, info);
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
return <Inner error={this.state.error} props={this.props} />;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const divStyles: React.CSSProperties = {
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
};
|
||||
|
||||
const ErrorBoundary = Catch(function (
|
||||
props: React.PropsWithChildren,
|
||||
error?: Error
|
||||
) {
|
||||
if (error) {
|
||||
return (
|
||||
<div style={divStyles}>
|
||||
<h2>
|
||||
There was an error on the page. Please reload the application and try
|
||||
again.
|
||||
</h2>
|
||||
<p />
|
||||
<p>{error.message}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return <>{props.children}</>;
|
||||
});
|
||||
|
||||
export default ErrorBoundary;
|
||||
@@ -0,0 +1 @@
|
||||
export { default as ErrorBoundary } from "./ErrorBoundary";
|
||||
@@ -0,0 +1,56 @@
|
||||
import styled from "@emotion/styled";
|
||||
import React from "react";
|
||||
|
||||
import MainNavigation from "../Navigation/MainNavigation";
|
||||
|
||||
const Root = styled("div")({
|
||||
background: "rgb(215, 215, 215)",
|
||||
});
|
||||
|
||||
const Container = styled("div")({
|
||||
alignItems: "stretch",
|
||||
display: "flex",
|
||||
margin: "0 auto",
|
||||
maxWidth: 1600,
|
||||
minHeight: "100vh",
|
||||
width: "100vw",
|
||||
});
|
||||
|
||||
const Nav = styled("nav")({
|
||||
background: "rgb(41, 62, 73)",
|
||||
color: "white",
|
||||
flex: "0 0 280px",
|
||||
padding: "8px 20px",
|
||||
|
||||
"@media (max-width: 600px)": {
|
||||
display: "none",
|
||||
},
|
||||
|
||||
"& a": {
|
||||
color: "white",
|
||||
},
|
||||
});
|
||||
|
||||
const Main = styled("main")({
|
||||
background: "rgb(245, 245, 245)",
|
||||
color: "rgb(25, 25, 25)",
|
||||
flex: "1 0 500px",
|
||||
padding: "8px 20px",
|
||||
});
|
||||
|
||||
const MainLayout: React.FC<React.PropsWithChildren> = (props) => {
|
||||
const { children } = props;
|
||||
|
||||
return (
|
||||
<Root>
|
||||
<Container>
|
||||
<Nav>
|
||||
<MainNavigation />
|
||||
</Nav>
|
||||
<Main>{children}</Main>
|
||||
</Container>
|
||||
</Root>
|
||||
);
|
||||
};
|
||||
|
||||
export default MainLayout;
|
||||
@@ -0,0 +1,8 @@
|
||||
import styled from "@emotion/styled";
|
||||
import { Link as RouterLink } from "react-router-dom";
|
||||
|
||||
const Link = styled(RouterLink)({
|
||||
color: "rgb(35, 115, 220)",
|
||||
});
|
||||
|
||||
export default Link;
|
||||
@@ -0,0 +1 @@
|
||||
export { default as Link } from "./Link";
|
||||
@@ -0,0 +1,12 @@
|
||||
import React from "react";
|
||||
|
||||
const MainNavigation: React.FC = () => {
|
||||
return (
|
||||
<>
|
||||
<p>Contact</p>
|
||||
<a href="mailto:linkedin@c3c.cz">linkedin@c3c.cz</a>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default MainNavigation;
|
||||
@@ -0,0 +1,13 @@
|
||||
interface ConfigFromBackend {
|
||||
commitTime: string;
|
||||
}
|
||||
|
||||
interface MyWindow extends Window {
|
||||
APP_CONFIG?: ConfigFromBackend;
|
||||
}
|
||||
|
||||
declare const window: MyWindow;
|
||||
|
||||
export const BUILD_TIMESTAMP: Date = window.APP_CONFIG?.commitTime
|
||||
? new Date(window.APP_CONFIG.commitTime)
|
||||
: new Date();
|
||||
@@ -0,0 +1,10 @@
|
||||
import React from "react";
|
||||
import ReactDOM from "react-dom/client";
|
||||
|
||||
import App from "./App";
|
||||
|
||||
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>
|
||||
);
|
||||
@@ -0,0 +1,15 @@
|
||||
import React from "react";
|
||||
|
||||
import MainLayout from "../components/Layout/MainLayout";
|
||||
|
||||
const Dashboard: React.FC = () => {
|
||||
return (
|
||||
<MainLayout>
|
||||
<h1>Lukáš Čech</h1>
|
||||
<h2>DevOps Engineer</h2>
|
||||
<p>(For the lack of a better name)</p>
|
||||
</MainLayout>
|
||||
);
|
||||
};
|
||||
|
||||
export default Dashboard;
|
||||
@@ -0,0 +1,34 @@
|
||||
import styled from "@emotion/styled";
|
||||
import React from "react";
|
||||
import { defineMessages, useIntl } from "react-intl";
|
||||
|
||||
import { Link } from "../components/Link";
|
||||
|
||||
const messages = defineMessages({
|
||||
notFound: {
|
||||
defaultMessage: "Nothing to see here",
|
||||
id: "Router.NotFound",
|
||||
},
|
||||
});
|
||||
|
||||
const Root = styled("div")({
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
height: "100vh",
|
||||
width: "100vw",
|
||||
});
|
||||
|
||||
const NotFound = () => {
|
||||
const intl = useIntl();
|
||||
|
||||
return (
|
||||
<Root>
|
||||
<p>{intl.formatMessage(messages.notFound)}</p>
|
||||
<Link to="/">Go home</Link>
|
||||
</Root>
|
||||
);
|
||||
};
|
||||
|
||||
export default NotFound;
|
||||
@@ -0,0 +1,39 @@
|
||||
import React from "react";
|
||||
import { Outlet, RouterProvider } from "react-router-dom";
|
||||
import { createBrowserRouter } from "react-router-dom";
|
||||
|
||||
import { ErrorBoundary } from "../components/ErrorBoundary";
|
||||
import Dashboard from "./Dashboard";
|
||||
|
||||
const Layout: React.FC = () => {
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<Outlet />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
};
|
||||
|
||||
const NotFound = React.lazy(() => import("./NotFound"));
|
||||
|
||||
const router = createBrowserRouter([
|
||||
{
|
||||
path: "/",
|
||||
element: <Layout />,
|
||||
children: [
|
||||
{
|
||||
index: true,
|
||||
element: <Dashboard />,
|
||||
},
|
||||
{
|
||||
path: "*",
|
||||
element: <NotFound />,
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
const Router = (): JSX.Element => {
|
||||
return <RouterProvider router={router} />;
|
||||
};
|
||||
|
||||
export default Router;
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react",
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react-swc'
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
clearScreen: false,
|
||||
plugins: [react()],
|
||||
})
|
||||
@@ -0,0 +1,107 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
|
||||
"go.c3c.cz/cv/app/server/internal/version"
|
||||
)
|
||||
|
||||
type FrontendConfigDef struct {
|
||||
CommitTime string `json:"commitTime"`
|
||||
}
|
||||
|
||||
var (
|
||||
BindAddrPprof = confString("BIND_ADDR_PPROF", "localhost:6060", false)
|
||||
BindAddrHttp = confString("BIND_ADDR_HTTP", ":8080", false)
|
||||
|
||||
GraceTerminationDelay = confDuration("GRACE_TERMINATION_DELAY", 0)
|
||||
GraceTerminationLimit = confDuration("GRACE_TERMINATION_LIMIT", 10*time.Second)
|
||||
|
||||
LoggerConfig *zap.Config
|
||||
loggingLevel = confString("LOGGING_LEVEL", "info", false)
|
||||
|
||||
Frontend string
|
||||
)
|
||||
|
||||
func init() {
|
||||
b, err := json.Marshal(FrontendConfigDef{
|
||||
CommitTime: version.CommitTime.Format(time.RFC3339),
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
Frontend = string(b)
|
||||
|
||||
zapConfig := confString("LOGGER_CONFIG", "", false)
|
||||
|
||||
var l zapcore.Level
|
||||
if err := l.UnmarshalText([]byte(loggingLevel)); err != nil {
|
||||
log.Fatal(fmt.Errorf("could not create debug level from env: %w", err))
|
||||
}
|
||||
|
||||
if zapConfig != "" {
|
||||
if err := json.Unmarshal([]byte(zapConfig), &LoggerConfig); err != nil {
|
||||
log.Fatal(fmt.Errorf("could not create logging configuration from env: %w", err))
|
||||
}
|
||||
|
||||
// Warn if both logger config and logging level are specified
|
||||
_, loggingLevelPresent := os.LookupEnv("LOGGING_LEVEL")
|
||||
if loggingLevelPresent {
|
||||
log.Println("cannot have both LOGGING_CONFIG and LOGGING_LEVEL environment configuration values")
|
||||
LoggerConfig.Level = zap.NewAtomicLevelAt(l)
|
||||
}
|
||||
} else {
|
||||
loggerConfig := zap.NewProductionConfig()
|
||||
encoderConfig := zap.NewProductionEncoderConfig()
|
||||
encoderConfig.TimeKey = "t"
|
||||
encoderConfig.LevelKey = "l"
|
||||
encoderConfig.CallerKey = "c"
|
||||
encoderConfig.MessageKey = "m"
|
||||
encoderConfig.StacktraceKey = "s"
|
||||
encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
|
||||
encoderConfig.EncodeTime = zapcore.RFC3339NanoTimeEncoder
|
||||
encoderConfig.EncodeDuration = zapcore.MillisDurationEncoder
|
||||
encoderConfig.EncodeCaller = zapcore.ShortCallerEncoder
|
||||
|
||||
loggerConfig.EncoderConfig = encoderConfig
|
||||
loggerConfig.Level = zap.NewAtomicLevelAt(l)
|
||||
loggerConfig.Encoding = "json"
|
||||
|
||||
LoggerConfig = &loggerConfig
|
||||
}
|
||||
}
|
||||
|
||||
const requiredErrorF = `required variable "%s" not set`
|
||||
|
||||
func confString(name string, defaultValue string, required bool) string {
|
||||
val, present := os.LookupEnv(name)
|
||||
if !present {
|
||||
if required {
|
||||
log.Fatalf(requiredErrorF, name)
|
||||
}
|
||||
|
||||
val = defaultValue
|
||||
}
|
||||
return val
|
||||
}
|
||||
|
||||
func confDuration(name string, defaultValue time.Duration) (val time.Duration) {
|
||||
sVal, present := os.LookupEnv(name)
|
||||
if !present {
|
||||
val = defaultValue
|
||||
} else {
|
||||
var err error
|
||||
val, err = time.ParseDuration(sVal)
|
||||
if err != nil {
|
||||
log.Fatalf(`cannot parse duration variable "%s"`, name)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package files
|
||||
|
||||
import (
|
||||
"embed"
|
||||
)
|
||||
|
||||
//go:embed data/public/*
|
||||
var Public embed.FS
|
||||
@@ -0,0 +1,275 @@
|
||||
package httpserver
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"html/template"
|
||||
"io"
|
||||
"io/fs"
|
||||
"io/ioutil"
|
||||
"mime"
|
||||
"net/http"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/improbable-eng/grpc-web/go/grpcweb"
|
||||
"go.uber.org/zap"
|
||||
"golang.org/x/oauth2"
|
||||
|
||||
"go.c3c.cz/cv/app/server/internal/files"
|
||||
"go.c3c.cz/cv/app/server/internal/version"
|
||||
)
|
||||
|
||||
const refreshTokenCookieName = "rt"
|
||||
|
||||
type handler struct {
|
||||
oauth2 *oauth2.Config
|
||||
indexTemplate *template.Template
|
||||
looseCORS bool
|
||||
grpcWebServer *grpcweb.WrappedGrpcServer
|
||||
frontendConfig string
|
||||
logger *zap.Logger
|
||||
refreshTokenCookieDomain string
|
||||
}
|
||||
|
||||
type accessToken struct {
|
||||
Token string `json:"token"`
|
||||
ExpiresIn int64 `json:"expiresIn"`
|
||||
}
|
||||
|
||||
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if h.looseCORS {
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, x-grpc-web, Authorization, x-user-agent")
|
||||
}
|
||||
|
||||
switch {
|
||||
case h.grpcWebServer.IsGrpcWebRequest(r):
|
||||
h.grpcWebServer.ServeHTTP(w, r)
|
||||
case r.Method == http.MethodPost && r.URL.Path == "/auth/login":
|
||||
h.handleLogin(w, r)
|
||||
case r.Method == http.MethodPost && r.URL.Path == "/auth/logout":
|
||||
h.handleLogout(w, r)
|
||||
case r.Method == http.MethodPost && r.URL.Path == "/auth/refresh":
|
||||
h.handleRefreshToken(w, r)
|
||||
default:
|
||||
f, err := files.Public.Open(path.Join("data", "public", r.URL.Path))
|
||||
if err != nil {
|
||||
h.serveIndex(w)
|
||||
return
|
||||
}
|
||||
|
||||
fi, err := f.Stat()
|
||||
if err != nil || fi.IsDir() {
|
||||
h.serveIndex(w)
|
||||
return
|
||||
}
|
||||
|
||||
h.serveFile(w, r, version.CommitTime, f)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *handler) serveFile(w http.ResponseWriter, r *http.Request, modtime time.Time, f fs.File) {
|
||||
if !modtime.IsZero() {
|
||||
ims := r.Header.Get("If-Modified-Since")
|
||||
modtime = modtime.Truncate(time.Second)
|
||||
if t, err := http.ParseTime(ims); err == nil && !modtime.After(t) {
|
||||
w.WriteHeader(http.StatusNotModified)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Last-Modified", modtime.UTC().Format(http.TimeFormat))
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", mime.TypeByExtension(filepath.Ext(r.URL.Path)))
|
||||
|
||||
if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
|
||||
w.Header().Set("Content-Encoding", "gzip")
|
||||
gw, err := gzip.NewWriterLevel(w, gzip.DefaultCompression)
|
||||
if err != nil {
|
||||
h.logger.Warn("Could not create gzip writer", zap.Error(err))
|
||||
return
|
||||
}
|
||||
if n, _ := io.Copy(gw, f); n == 0 {
|
||||
w.Header().Del("Content-Encoding")
|
||||
gw.Reset(ioutil.Discard)
|
||||
}
|
||||
err = gw.Close()
|
||||
|
||||
if err != nil {
|
||||
h.logger.Warn("Could not close gzip writer", zap.Error(err))
|
||||
return
|
||||
}
|
||||
} else {
|
||||
_, err := io.Copy(w, f)
|
||||
if err != nil {
|
||||
h.logger.Warn("Could not write file response", zap.Error(err))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *handler) serveIndex(w http.ResponseWriter) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
|
||||
if h.indexTemplate == nil {
|
||||
_, _ = w.Write([]byte("no index"))
|
||||
return
|
||||
}
|
||||
|
||||
token := make([]byte, 12)
|
||||
_, err := rand.Read(token)
|
||||
if err != nil {
|
||||
h.logger.Warn("Could not create random csp token", zap.Error(err))
|
||||
return
|
||||
}
|
||||
|
||||
data := indexData{
|
||||
Config: h.frontendConfig,
|
||||
CspNonce: base64.RawStdEncoding.EncodeToString(token),
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Security-Policy", "script-src 'self' 'nonce-"+data.CspNonce+"' 'unsafe-eval'")
|
||||
w.Header().Set("X-Frame-Options", "DENY")
|
||||
w.Header().Set("X-XSS-Protection", "1; mode=block")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Referrer-Policy", "same-origin")
|
||||
w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
|
||||
w.Header().Set("Permissions-Policy", "accelerometer=(), camera=(), geolocation=(), microphone=(), payment=(), usb=()")
|
||||
|
||||
err = h.indexTemplate.Execute(w, data)
|
||||
if err != nil {
|
||||
h.logger.Warn("Could not execute index template", zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
type authData struct {
|
||||
Email string
|
||||
Password string
|
||||
}
|
||||
|
||||
func (h *handler) handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
var ad authData
|
||||
|
||||
if err := json.NewDecoder(r.Body).Decode(&ad); err != nil {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
err = json.NewEncoder(w).Encode(map[string]string{"error": "invalid json"})
|
||||
if err != nil {
|
||||
h.logger.Error("Could not encode json response with invalid json error", zap.Error(err))
|
||||
}
|
||||
return
|
||||
}
|
||||
r.Body.Close()
|
||||
|
||||
tok, err := h.oauth2.PasswordCredentialsToken(r.Context(), ad.Email, ad.Password)
|
||||
if err != nil {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
err = json.NewEncoder(w).Encode(map[string]string{"error": "wrong credentials"})
|
||||
if err != nil {
|
||||
h.logger.Error("Could not encode json response with wrong credentials error", zap.Error(err))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if tok.RefreshToken != "" {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Domain: h.refreshTokenCookieDomain,
|
||||
Path: "/auth/refresh",
|
||||
Name: refreshTokenCookieName,
|
||||
Value: tok.RefreshToken,
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
Secure: isSecure(r),
|
||||
})
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
err = json.NewEncoder(w).Encode(accessToken{
|
||||
Token: tok.AccessToken,
|
||||
ExpiresIn: int64(time.Until(tok.Expiry) / time.Second),
|
||||
})
|
||||
if err != nil {
|
||||
h.logger.Error("Could not encode access token json", zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
func (h *handler) handleRefreshToken(w http.ResponseWriter, r *http.Request) {
|
||||
cookie, err := r.Cookie(refreshTokenCookieName)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
tok, err := h.oauth2.TokenSource(r.Context(), &oauth2.Token{RefreshToken: cookie.Value}).Token()
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
err = json.NewEncoder(w).Encode(accessToken{
|
||||
Token: tok.AccessToken,
|
||||
ExpiresIn: int64(time.Until(tok.Expiry) / time.Second),
|
||||
})
|
||||
if err != nil {
|
||||
h.logger.Error("Could not encode refresh token response", zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
func (h *handler) handleLogout(w http.ResponseWriter, r *http.Request) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Domain: h.refreshTokenCookieDomain,
|
||||
Path: "/auth/refresh",
|
||||
Name: refreshTokenCookieName,
|
||||
MaxAge: -1,
|
||||
HttpOnly: true,
|
||||
Secure: isSecure(r),
|
||||
})
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, err := w.Write([]byte("ok"))
|
||||
if err != nil {
|
||||
h.logger.Error("Could not write logout response", zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
type indexData struct {
|
||||
Config string
|
||||
CspNonce string
|
||||
}
|
||||
|
||||
var (
|
||||
httpHeaderXForwardedProto = http.CanonicalHeaderKey("X-Forwarded-Proto")
|
||||
httpHeaderXForwardedScheme = http.CanonicalHeaderKey("X-Forwarded-Scheme")
|
||||
httpHeaderForwarded = http.CanonicalHeaderKey("Forwarded")
|
||||
protoRegex = regexp.MustCompile(`(?i)(?:proto=)(https|http)`)
|
||||
)
|
||||
|
||||
func isSecure(r *http.Request) bool {
|
||||
if strings.EqualFold(r.URL.Scheme, "https") {
|
||||
return true
|
||||
}
|
||||
|
||||
var scheme string
|
||||
|
||||
if proto := r.Header.Get(httpHeaderXForwardedProto); proto != "" {
|
||||
scheme = strings.ToLower(proto)
|
||||
} else if proto = r.Header.Get(httpHeaderXForwardedScheme); proto != "" {
|
||||
scheme = strings.ToLower(proto)
|
||||
} else if proto = r.Header.Get(httpHeaderForwarded); proto != "" {
|
||||
if match := protoRegex.FindStringSubmatch(proto); len(match) > 1 {
|
||||
scheme = strings.ToLower(match[1])
|
||||
}
|
||||
}
|
||||
|
||||
return scheme == "https"
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package httpserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"mime"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/improbable-eng/grpc-web/go/grpcweb"
|
||||
"go.uber.org/zap"
|
||||
"golang.org/x/oauth2"
|
||||
|
||||
"go.c3c.cz/cv/app/server/internal/files"
|
||||
)
|
||||
|
||||
func init() {
|
||||
err := mime.AddExtensionType(".ico", "image/x-icon")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
err = mime.AddExtensionType(".json", "application/json; charset=utf-8")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
type Options struct {
|
||||
BindAddr string
|
||||
OAuth2 *oauth2.Config
|
||||
GrpcWebServer *grpcweb.WrappedGrpcServer
|
||||
FrontendConfig string
|
||||
Logger *zap.Logger
|
||||
LooseCORS bool
|
||||
RefreshTokenCookieDomain string
|
||||
RequireIndex bool
|
||||
}
|
||||
|
||||
type server struct{ http.Server }
|
||||
|
||||
func New(options *Options) (*server, error) {
|
||||
handler := &handler{
|
||||
oauth2: options.OAuth2,
|
||||
grpcWebServer: options.GrpcWebServer,
|
||||
frontendConfig: options.FrontendConfig,
|
||||
logger: options.Logger,
|
||||
looseCORS: options.LooseCORS,
|
||||
refreshTokenCookieDomain: options.RefreshTokenCookieDomain,
|
||||
}
|
||||
|
||||
httpSrv := &server{
|
||||
http.Server{
|
||||
Addr: options.BindAddr,
|
||||
Handler: handler,
|
||||
},
|
||||
}
|
||||
|
||||
index, err := files.Public.Open("data/public/index.html")
|
||||
if err != nil {
|
||||
if !options.RequireIndex {
|
||||
return httpSrv, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("could not open index.html: %w", err)
|
||||
}
|
||||
|
||||
fi, err := index.Stat()
|
||||
if err != nil || fi.IsDir() {
|
||||
if !options.RequireIndex {
|
||||
return httpSrv, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("invalid index.html: %w", err)
|
||||
}
|
||||
|
||||
tb, err := ioutil.ReadAll(index)
|
||||
if err != nil {
|
||||
if !options.RequireIndex {
|
||||
return httpSrv, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("could not read index.html: %w", err)
|
||||
}
|
||||
|
||||
handler.indexTemplate, err = template.New("index").Parse(string(tb))
|
||||
if err != nil {
|
||||
if !options.RequireIndex {
|
||||
return httpSrv, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("could not parse index.html: index.html: %w", err)
|
||||
}
|
||||
|
||||
return httpSrv, nil
|
||||
}
|
||||
|
||||
func (s *server) ShutdownWithDelay(delay time.Duration, limit time.Duration) {
|
||||
h, ok := s.Handler.(*handler)
|
||||
|
||||
var logger *zap.Logger
|
||||
if ok {
|
||||
logger = h.logger
|
||||
} else {
|
||||
logger = zap.L()
|
||||
}
|
||||
|
||||
if delay > 0 {
|
||||
logger.Info(fmt.Sprintf("Waiting %s for incoming requests\n", delay))
|
||||
time.Sleep(delay)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), limit)
|
||||
defer cancel()
|
||||
|
||||
logger.Info("Gracefully shutting down http server")
|
||||
if err := s.Shutdown(ctx); err != nil {
|
||||
logger.Error("Failed to shutdown http server", zap.Error(err))
|
||||
} else {
|
||||
logger.Info("Http server was stopped")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package pprofserver
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type Options struct {
|
||||
BindAddr string
|
||||
LogLevelHandler http.Handler
|
||||
Logger *zap.Logger
|
||||
}
|
||||
|
||||
type server struct {
|
||||
addr string
|
||||
logger *zap.Logger
|
||||
ready bool
|
||||
}
|
||||
|
||||
func New(options Options) *server {
|
||||
s := &server{
|
||||
addr: options.BindAddr,
|
||||
logger: options.Logger,
|
||||
}
|
||||
|
||||
http.Handle("/log/level", options.LogLevelHandler)
|
||||
http.HandleFunc("/readyz", s.handleReady)
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *server) ListenAndServe() error {
|
||||
return http.ListenAndServe(s.addr, nil)
|
||||
}
|
||||
|
||||
func (s *server) handleReady(w http.ResponseWriter, _ *http.Request) {
|
||||
s.logger.Debug("Handling healthcheck request", zap.Bool("ready", s.ready))
|
||||
|
||||
if s.ready {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
_, err := w.Write([]byte("shutting down"))
|
||||
if err != nil {
|
||||
s.logger.Error("Could not write ready response", zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *server) SetReady() {
|
||||
s.ready = true
|
||||
}
|
||||
|
||||
func (s *server) SetNotReady() {
|
||||
s.ready = false
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package version
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
JSON []byte
|
||||
|
||||
Commit string
|
||||
CommitTime time.Time
|
||||
Tag string
|
||||
|
||||
commitTime string
|
||||
repoUrl string
|
||||
)
|
||||
|
||||
func init() {
|
||||
t, _ := time.Parse(time.RFC3339, commitTime)
|
||||
CommitTime = t.In(time.UTC)
|
||||
|
||||
type v struct {
|
||||
Source string `json:"source,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
Commit string `json:"commit,omitempty"`
|
||||
CommitTime time.Time `json:"commitTime,omitempty"`
|
||||
}
|
||||
|
||||
JSON, _ = json.Marshal(v{
|
||||
Source: repoUrl,
|
||||
Version: Tag,
|
||||
Commit: Commit,
|
||||
CommitTime: CommitTime,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
_ "net/http/pprof"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"go.uber.org/zap"
|
||||
|
||||
"go.c3c.cz/cv/app/server/internal/config"
|
||||
"go.c3c.cz/cv/app/server/internal/httpserver"
|
||||
"go.c3c.cz/cv/app/server/internal/pprofserver"
|
||||
"go.c3c.cz/cv/app/server/internal/version"
|
||||
)
|
||||
|
||||
func main() {
|
||||
defer handleExit()
|
||||
|
||||
notice := "Starting version "
|
||||
if version.Tag != "" {
|
||||
notice += version.Tag
|
||||
} else {
|
||||
notice += "latest"
|
||||
}
|
||||
if version.Commit != "" {
|
||||
notice = fmt.Sprintf("%s (%s)", notice, version.Commit)
|
||||
}
|
||||
|
||||
var logger *zap.Logger
|
||||
var err error
|
||||
|
||||
logger, err = config.LoggerConfig.Build()
|
||||
|
||||
if err != nil {
|
||||
fmt.Println(notice)
|
||||
fmt.Println(version.CommitTime.Format("Committed at 2006/01/02 15:04:05 MST"))
|
||||
|
||||
panic(Exit{fmt.Errorf("logger creation failed")})
|
||||
}
|
||||
|
||||
logger.Info(
|
||||
"App initializing",
|
||||
zap.String("version", version.Tag),
|
||||
zap.String("commit", version.Commit),
|
||||
zap.Time("commitTime", version.CommitTime),
|
||||
)
|
||||
|
||||
defer func() {
|
||||
_ = logger.Sync()
|
||||
}()
|
||||
|
||||
httpSrv, err := httpserver.New(&httpserver.Options{
|
||||
BindAddr: config.BindAddrHttp,
|
||||
FrontendConfig: config.Frontend,
|
||||
Logger: logger,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error("HTTP server creation failed", zap.Error(err))
|
||||
panic(Exit{err})
|
||||
}
|
||||
|
||||
quit := struct {
|
||||
os chan os.Signal
|
||||
pprof chan error
|
||||
http chan error
|
||||
}{
|
||||
os: make(chan os.Signal, 1),
|
||||
pprof: make(chan error, 1),
|
||||
http: make(chan error, 1),
|
||||
}
|
||||
|
||||
pprofSrv := pprofserver.New(pprofserver.Options{
|
||||
BindAddr: config.BindAddrPprof,
|
||||
Logger: logger,
|
||||
LogLevelHandler: config.LoggerConfig.Level,
|
||||
})
|
||||
|
||||
// Pprof server.
|
||||
go func() {
|
||||
logger.Info("debug server was started", zap.String("BindAddr", config.BindAddrPprof))
|
||||
quit.pprof <- pprofSrv.ListenAndServe()
|
||||
}()
|
||||
|
||||
go func() {
|
||||
logger.Info("http server was started", zap.String("BindAddr", config.BindAddrHttp))
|
||||
pprofSrv.SetReady()
|
||||
err := httpSrv.ListenAndServe()
|
||||
if err != http.ErrServerClosed {
|
||||
quit.http <- err
|
||||
}
|
||||
}()
|
||||
|
||||
logger.Info("application started")
|
||||
|
||||
signal.Notify(quit.os, os.Interrupt, syscall.SIGTERM)
|
||||
|
||||
select {
|
||||
case s := <-quit.os:
|
||||
sig, _ := s.(syscall.Signal)
|
||||
logger.Info("Signal received\n", zap.Int("signal", int(sig)))
|
||||
pprofSrv.SetNotReady()
|
||||
httpSrv.ShutdownWithDelay(config.GraceTerminationDelay, config.GraceTerminationLimit)
|
||||
case err := <-quit.pprof:
|
||||
logger.Error("app shutdown was triggered by a pprof server error", zap.Error(err))
|
||||
httpSrv.ShutdownWithDelay(config.GraceTerminationDelay, config.GraceTerminationLimit)
|
||||
case err := <-quit.http:
|
||||
logger.Error("app shutdown was triggered by an http server error", zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
type Exit struct {
|
||||
err error
|
||||
}
|
||||
|
||||
func handleExit() {
|
||||
if e := recover(); e != nil {
|
||||
if exit, ok := e.(Exit); ok {
|
||||
fmt.Println(exit.err)
|
||||
os.Exit(1)
|
||||
}
|
||||
panic(e)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user