Initial commit

This commit is contained in:
2021-04-10 07:58:01 +02:00
commit 4bb38a797c
49 changed files with 12483 additions and 0 deletions

44
web/frontend.go Normal file
View File

@@ -0,0 +1,44 @@
// +build !embed
package web
import (
"io"
"net/http"
"os"
"path/filepath"
)
func (s *Server) FrontendHandler(frontendDir string) http.HandlerFunc {
fs := http.FileServer(http.Dir(frontendDir))
return fs.ServeHTTP
}
func (s *Server) IndexHandler(frontendDir string) http.HandlerFunc {
fs := http.FileServer(http.Dir(frontendDir))
fn := func(w http.ResponseWriter, r *http.Request) {
fname := filepath.Join(frontendDir, r.URL.Path)
_, err := os.Stat(fname)
if os.IsNotExist(err) {
serveIndex(frontendDir).ServeHTTP(w, r)
return
}
fs.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func serveIndex(frontendDir string) http.HandlerFunc {
fn := func(w http.ResponseWriter, r *http.Request) {
fname := filepath.Join(frontendDir, "index.html")
f, err := os.Open(fname)
if err != nil {
panic(err)
}
defer f.Close()
io.Copy(w, f)
}
return fn
}

View File

@@ -0,0 +1,3 @@
> 1%
last 2 versions
not dead

View File

@@ -0,0 +1,7 @@
[*.{js,jsx,ts,tsx,vue}]
indent_style = space
indent_size = 2
end_of_line = lf
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 100

19
web/frontend/.eslintrc.js Normal file
View File

@@ -0,0 +1,19 @@
module.exports = {
root: true,
env: {
node: true,
},
extends: [
'plugin:vue/essential',
'@vue/airbnb',
'@vue/typescript/recommended',
],
parserOptions: {
ecmaVersion: 2020,
},
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'implicit-arrow-linebreak': 'warn',
},
};

23
web/frontend/.gitignore vendored Normal file
View File

@@ -0,0 +1,23 @@
.DS_Store
node_modules
/dist
# local env files
.env.local
.env.*.local
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

24
web/frontend/README.md Normal file
View File

@@ -0,0 +1,24 @@
# vue-frontend
## Project setup
```
yarn install
```
### Compiles and hot-reloads for development
```
yarn serve
```
### Compiles and minifies for production
```
yarn build
```
### Lints and fixes files
```
yarn lint
```
### Customize configuration
See [Configuration Reference](https://cli.vuejs.org/config/).

View File

@@ -0,0 +1,5 @@
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset',
],
};

48
web/frontend/package.json Normal file
View File

@@ -0,0 +1,48 @@
{
"name": "apiary-frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"@fontsource/rubik": "^4.2.2",
"@fontsource/secular-one": "^4.2.2",
"axios": "^0.21.1",
"bootstrap": "^4.6.0",
"bootstrap-vue": "^2.21.2",
"chart.js": "^3.0.2",
"core-js": "^3.6.5",
"d3": "^6.6.2",
"d3-svg-legend": "^2.25.6",
"faker": "^5.5.2",
"randomcolor": "^0.6.2",
"s-ago": "^2.2.0",
"vue": "^2.6.11",
"vue-class-component": "^7.2.3",
"vue-property-decorator": "^9.1.2",
"vue-router": "^3.5.1"
},
"devDependencies": {
"@types/d3": "^6.3.0",
"@types/faker": "^5.5.1",
"@types/randomcolor": "^0.5.5",
"@typescript-eslint/eslint-plugin": "^4.18.0",
"@typescript-eslint/parser": "^4.18.0",
"@vue/cli-plugin-babel": "~4.5.0",
"@vue/cli-plugin-eslint": "~4.5.0",
"@vue/cli-plugin-typescript": "~4.5.0",
"@vue/cli-service": "~4.5.0",
"@vue/eslint-config-airbnb": "^5.0.2",
"@vue/eslint-config-typescript": "^7.0.0",
"eslint": "^6.7.2",
"eslint-plugin-import": "^2.20.2",
"eslint-plugin-vue": "^6.2.2",
"sass": "^1.26.5",
"sass-loader": "^8.0.2",
"typescript": "~4.1.5",
"vue-template-compiler": "^2.6.11"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -0,0 +1,21 @@
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title>apiary.t-juice.club</title>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled.
Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

63
web/frontend/src/App.vue Normal file
View File

@@ -0,0 +1,63 @@
<template>
<div id="app">
<div id="apiary-navbar">
<b-navbar type="dark" variant="dark">
<b-navbar-brand href="#">
<img
alt="logo"
src="logo192.png"
width="29"
height="29"
class="d-inline-block align-top"
/>
apiary.t-juice.club
</b-navbar-brand>
<b-navbar-nav>
<b-nav-item :to="'/'">Home</b-nav-item>
<b-nav-item :to="'/hello'">Hello</b-nav-item>
<b-nav-item :to="'/stats'">Stats</b-nav-item>
<b-nav-item :to="'/attempts'">Attempts</b-nav-item>
</b-navbar-nav>
</b-navbar>
</div>
<router-view></router-view>
<!-- <img alt="Vue logo" src="./assets/logo.png" /> -->
<!-- <HelloWorld msg="Welcome to Your Vue.js + TypeScript App" /> -->
<!-- <AttemptList items="{ testAttempts }" /> -->
</div>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import HelloWorld from '@/components/HelloWorld.vue';
import AttemptList from '@/components/AttemptList.vue';
import Stats from '@/components/Stats.vue';
@Component({
components: {
HelloWorld,
AttemptList,
Stats,
},
})
export default class App extends Vue {}
</script>
<style lang="scss">
$font-stack: 'Secular One';
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 0;
}
.navbar-brand {
font-family: 'Secular One', sans-serif;
}
.navbar-nav a {
font-family: 'Rubik';
}
</style>

View File

@@ -0,0 +1,8 @@
import { ApiaryAPI, LoginAttempt } from "@/apiary/apiary";
export class ApiaryDummyClient implements ApiaryAPI {
streamLoginAttempts(): any {
return 'a';
}
}

View File

@@ -0,0 +1,35 @@
import FakerStatic from 'faker';
export interface LoginAttempt {
readonly date: string;
readonly remoteIP: string;
readonly username: string;
readonly password: string;
readonly sshClientVersion: string;
readonly connectionUUID: string;
}
export interface StatResult {
name: string;
count: number;
}
export interface ApiaryAPI {
streamLoginAttempts(): ReadableStream<LoginAttempt>;
}
export function fakeAttempt(): LoginAttempt {
return {
date: FakerStatic.date.recent().toLocaleDateString(),
remoteIP: FakerStatic.internet.ip(),
username: FakerStatic.internet.userName(),
password: FakerStatic.internet.password(),
sshClientVersion: FakerStatic.lorem.words(2),
connectionUUID: FakerStatic.datatype.uuid(),
};
}
export function fakeAttemptStream(): EventSource {
const es = new EventSource('/stream');
return es;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

View File

@@ -0,0 +1,85 @@
<template>
<div class="attemptlist">
<h1>Attempt list</h1>
<p>
<b-table
striped
hover
:items="prettiedAttempts"
:fields="fields"
></b-table>
</p>
</div>
</template>
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import { BvTableFieldArray } from 'bootstrap-vue';
import ago from 's-ago';
import { LoginAttempt, fakeAttempt, fakeAttemptStream } from '@/apiary/apiary';
@Component
export default class AttemptList extends Vue {
@Prop() private items!: LoginAttempt[];
attempts: LoginAttempt[];
fields: BvTableFieldArray = [
{
key: 'date',
sortable: true,
// formatter: (value: string): string => ago(new Date(value)),
sortByFormatted: false,
},
{
key: 'username',
},
{
key: 'password',
},
{
key: 'remoteIP',
sortable: true,
},
];
constructor() {
super();
this.attempts = [];
}
prettiedAttempts(): LoginAttempt[] {
const prettied = this.attempts.map<LoginAttempt>((value: LoginAttempt) => ({
date: ago(new Date(value.date)),
remoteIP: value.remoteIP,
username: value.username,
password: value.password,
sshClientVersion: value.sshClientVersion,
connectionUUID: value.connectionUUID,
}));
return prettied;
}
mounted(): void {
/**
console.log(this);
const at: LoginAttempt[] = [];
for (let i = 0; i < 5; i += 1) {
at.push(fakeAttempt());
}
setInterval(() => {
at.push(fakeAttempt());
}, 1000);
*/
const attemptStream = fakeAttemptStream();
attemptStream.addEventListener('message', (ev: MessageEvent<string>) => {
console.log(ev);
const parsed: LoginAttempt = JSON.parse(ev.data);
this.attempts.unshift(parsed);
});
}
}
</script>

View File

@@ -0,0 +1,59 @@
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<p>
For a guide and recipes on how to configure / customize this project,<br>
check out the
<a href="https://cli.vuejs.org" target="_blank" rel="noopener">vue-cli documentation</a>.
</p>
<h3>Installed CLI Plugins</h3>
<ul>
<li><a href="https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel" target="_blank" rel="noopener">babel</a></li>
<li><a href="https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-typescript" target="_blank" rel="noopener">typescript</a></li>
<li><a href="https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-eslint" target="_blank" rel="noopener">eslint</a></li>
</ul>
<h3>Essential Links</h3>
<ul>
<li><a href="https://vuejs.org" target="_blank" rel="noopener">Core Docs</a></li>
<li><a href="https://forum.vuejs.org" target="_blank" rel="noopener">Forum</a></li>
<li><a href="https://chat.vuejs.org" target="_blank" rel="noopener">Community Chat</a></li>
<li><a href="https://twitter.com/vuejs" target="_blank" rel="noopener">Twitter</a></li>
<li><a href="https://news.vuejs.org" target="_blank" rel="noopener">News</a></li>
</ul>
<h3>Ecosystem</h3>
<ul>
<li><a href="https://router.vuejs.org" target="_blank" rel="noopener">vue-router</a></li>
<li><a href="https://vuex.vuejs.org" target="_blank" rel="noopener">vuex</a></li>
<li><a href="https://github.com/vuejs/vue-devtools#vue-devtools" target="_blank" rel="noopener">vue-devtools</a></li>
<li><a href="https://vue-loader.vuejs.org" target="_blank" rel="noopener">vue-loader</a></li>
<li><a href="https://github.com/vuejs/awesome-vue" target="_blank" rel="noopener">awesome-vue</a></li>
</ul>
</div>
</template>
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
@Component
export default class HelloWorld extends Vue {
@Prop() private msg!: string;
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>

View File

@@ -0,0 +1,26 @@
<template>
<div class="stats">
<h1>Stats!</h1>
<stats-username />
</div>
</template>
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import StatsUsername from '@/components/StatsUsername.vue';
@Component({
components: {
StatsUsername,
},
})
export default class Stats extends Vue {
@Prop() private msg!: string;
}
</script>
<style lang="scss" scoped>
.stats {
align-content: center;
width: 70%;
}
</style>

View File

@@ -0,0 +1,67 @@
<template>
<div class="stats-container">
<h2>Top 10 usernames</h2>
<div class="chart-container">
<canvas id="chart" widht="400" height="400"></canvas>
</div>
</div>
</template>
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import { StatResult } from '@/apiary/apiary';
import axios from 'axios';
import Chart from 'chart.js/auto';
import randomColor from 'randomcolor';
@Component
export default class StatsUsername extends Vue {
@Prop() private msg!: string;
stats: StatResult[];
constructor() {
super();
this.stats = [];
}
mounted(): void {
axios
.get<StatResult[]>('/api/stats?type=username&limit=10')
.then((resp) => {
this.stats = resp.data;
this.renderPie();
});
}
renderPie(): void {
const elem = document.getElementById('chart') as HTMLCanvasElement;
const ctx = elem.getContext('2d') as CanvasRenderingContext2D;
const sortedStats = this.stats.sort();
const values = sortedStats.map((s) => s.count);
const headers = sortedStats.map((s) => s.name);
const colors = sortedStats.map(() => randomColor());
const chart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: headers,
options: {},
datasets: [
{
data: values,
backgroundColor: colors,
},
],
},
});
}
}
</script>
<style lang="scss" scoped>
.chart-container {
max-width: 500px;
max-height: 500px;
}
</style>

64
web/frontend/src/main.ts Normal file
View File

@@ -0,0 +1,64 @@
import Vue from 'vue';
import { BootstrapVue, IconsPlugin } from 'bootstrap-vue';
import VueRouter, { RouteConfig } from 'vue-router';
import AttemptList from '@/components/AttemptList.vue';
import HelloWorld from '@/components/HelloWorld.vue';
import Stats from '@/components/Stats.vue';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap-vue/dist/bootstrap-vue.css';
import '@fontsource/rubik';
import '@fontsource/secular-one';
import { LoginAttempt } from '@/apiary/apiary';
import App from './App.vue';
Vue.config.productionTip = false;
// Make BootstrapVue available throughout your project
Vue.use(BootstrapVue);
// Optionally install the BootstrapVue icon components plugin
Vue.use(IconsPlugin);
Vue.use(VueRouter);
Vue.use(VueRouter);
const routes: Array<RouteConfig> = [
{
path: '/',
name: 'Home',
component: HelloWorld,
alias: '/home',
},
{
path: '/hello',
name: 'Hello',
component: HelloWorld,
props: {
default: true,
msg: 'LOL',
},
},
{
path: '/attempts',
name: 'Attempt List',
component: AttemptList,
props: {
// items: testAttempts,
},
},
{
path: '/stats',
name: 'Stats',
component: Stats,
},
];
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes,
});
new Vue({
router,
render: (h) => h(App),
}).$mount('#app');

View File

@@ -0,0 +1,27 @@
import Vue from 'vue';
import VueRouter, { RouteConfig } from 'vue-router';
import AttemptList from "../components/Simulator.vue";
import HelloWorld from "../components/HelloWorld.vue";
Vue.use(VueRouter);
const routes: Array<RouteConfig> = [
{
path: '/',
name: 'Home',
component: HelloWorld
},
{
path: '/attempts',
name: 'Attempt List',
component: AttemptList
}
];
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
});
export default router;

13
web/frontend/src/shims-tsx.d.ts vendored Normal file
View File

@@ -0,0 +1,13 @@
import Vue, { VNode } from 'vue';
declare global {
namespace JSX {
// tslint:disable no-empty-interface
interface Element extends VNode {}
// tslint:disable no-empty-interface
interface ElementClass extends Vue {}
interface IntrinsicElements {
[elem: string]: any
}
}
}

5
web/frontend/src/shims-vue.d.ts vendored Normal file
View File

@@ -0,0 +1,5 @@
declare module '*.vue' {
import Vue from 'vue';
export default Vue;
}

View File

@@ -0,0 +1,40 @@
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"moduleResolution": "node",
"experimentalDecorators": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"types": [
"webpack-env"
],
"paths": {
"@/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}

9954
web/frontend/yarn.lock Normal file

File diff suppressed because it is too large Load Diff

52
web/frontend_embed.go Normal file
View File

@@ -0,0 +1,52 @@
// +build embed
package web
import (
"embed"
"io"
"io/fs"
"net/http"
"path/filepath"
"strings"
)
//go:embed frontend/dist
var static embed.FS
func (s *Server) IndexHandler(frontendDir string) http.HandlerFunc {
dir, err := fs.Sub(static, "frontend/dist")
if err != nil {
panic(err)
}
fileSrv := http.FileServer(http.FS(dir))
fn := func(w http.ResponseWriter, r *http.Request) {
path := strings.TrimPrefix(r.URL.Path, "/")
_, err := dir.Open(path)
if err != nil {
serveIndex(frontendDir).ServeHTTP(w, r)
return
}
fileSrv.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func serveIndex(frontendDir string) http.HandlerFunc {
dir, err := fs.Sub(static, "frontend/dist")
if err != nil {
panic(err)
}
fn := func(w http.ResponseWriter, r *http.Request) {
fname := filepath.Join("index.html")
f, err := dir.Open(fname)
if err != nil {
panic(err)
}
defer f.Close()
io.Copy(w, f)
}
return fn
}

37
web/middleware.go Normal file
View File

@@ -0,0 +1,37 @@
package web
import (
"net/http"
"time"
"github.com/go-chi/chi/v5/middleware"
)
// LoggingMiddleware is used for logging info about requests to the servers configured accesslogger.
func (s *Server) LoggingMiddleware(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
t1 := time.Now()
reqID := middleware.GetReqID(r.Context())
defer func() {
/*s.AccessLogger.Debugw(r.Method,
"path", r.URL.Path,
"request-headers", r.Header,
"response-headers", ww.Header(),
)
*/
s.AccessLogger.Infow(r.Method,
"path", r.URL.Path,
"status", ww.Status(),
"written", ww.BytesWritten(),
"remote_addr", r.RemoteAddr,
"processing_time_ms", time.Since(t1).Milliseconds(),
"req_id", reqID)
}()
next.ServeHTTP(ww, r)
}
return http.HandlerFunc(fn)
}

170
web/server.go Normal file
View File

@@ -0,0 +1,170 @@
package web
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"sync"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/google/uuid"
"github.uio.no/torjus/apiary/config"
"github.uio.no/torjus/apiary/honeypot"
"github.uio.no/torjus/apiary/honeypot/store"
"github.uio.no/torjus/apiary/models"
"go.uber.org/zap"
)
type Server struct {
http.Server
store store.LoginAttemptStore
ServerLogger *zap.SugaredLogger
AccessLogger *zap.SugaredLogger
honeypotServer *honeypot.HoneypotServer
attemptListenersLock sync.RWMutex
attemptListeners map[string]chan models.LoginAttempt
streamContext context.Context
}
func NewServer(cfg config.FrontendConfig, hs *honeypot.HoneypotServer, store store.LoginAttemptStore) *Server {
s := &Server{
ServerLogger: zap.NewNop().Sugar(),
AccessLogger: zap.NewNop().Sugar(),
store: store,
}
s.Addr = cfg.ListenAddr
r := chi.NewRouter()
// Setup middleware
r.Use(middleware.RealIP)
r.Use(middleware.RequestID)
r.Use(s.LoggingMiddleware)
r.Route("/", func(r chi.Router) {
r.Get("/*", s.IndexHandler("web/vue-frontend/dist"))
r.Get("/stream", s.HandlerAttemptStream)
r.Route("/api", func(r chi.Router) {
r.Use(middleware.SetHeader("Content-Type", "application/json"))
r.Get("/stats", s.HandlerStats)
})
})
s.Handler = r
s.honeypotServer = hs
s.attemptListeners = make(map[string]chan models.LoginAttempt)
streamCtx, streamCancel := context.WithCancel(context.Background())
s.streamContext = streamCtx
s.RegisterOnShutdown(func() {
streamCancel()
})
hs.AddLoginCallback(func(l models.LoginAttempt) {
s.attemptListenersLock.RLock()
defer s.attemptListenersLock.RUnlock()
for i := range s.attemptListeners {
s.attemptListeners[i] <- l
}
})
return s
}
func (s *Server) addAttemptListener() (string, chan models.LoginAttempt) {
ch := make(chan models.LoginAttempt)
s.attemptListenersLock.Lock()
defer s.attemptListenersLock.Unlock()
id := uuid.Must(uuid.NewRandom())
s.attemptListeners[id.String()] = ch
return id.String(), ch
}
func (s *Server) closeAttemptListener(id string) {
s.attemptListenersLock.Lock()
defer s.attemptListenersLock.Unlock()
ch := s.attemptListeners[id]
close(ch)
delete(s.attemptListeners, id)
}
func (s *Server) HandlerAttemptStream(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Access-Control-Allow-Origin", "*")
id, ch := s.addAttemptListener()
defer s.closeAttemptListener(id)
flusher := w.(http.Flusher)
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case l := <-ch:
data, err := json.Marshal(l)
if err != nil {
return
}
_, err = io.WriteString(w, fmt.Sprintf("data: %s\n\n", string(data)))
if err != nil {
s.ServerLogger.Warnw("Error writing event", "error", err)
}
flusher.Flush()
case <-s.streamContext.Done():
return
case <-r.Context().Done():
return
case <-ticker.C:
if _, err := io.WriteString(w, ": %s\n\n"); err != nil {
s.ServerLogger.Warnw("Error writing event", "error", err)
}
}
}
}
func (s *Server) HandlerStats(w http.ResponseWriter, r *http.Request) {
statType := store.LoginStats(r.URL.Query().Get("type"))
if statType == store.LoginStatsUndefined {
statType = store.LoginStatsPasswords
}
var limit int
limitString := r.URL.Query().Get("limit")
limit, err := strconv.Atoi(limitString)
if err != nil {
limit = 0
}
stats, err := s.store.Stats(statType, limit)
if err != nil {
s.WriteAPIError(w, r, http.StatusInternalServerError, "Error fetching stats")
return
}
encoder := json.NewEncoder(w)
if err := encoder.Encode(stats); err != nil {
s.ServerLogger.Debugf("Error encoding or writing response", "remote_ip", r.RemoteAddr, "error", err)
}
}
type APIErrorResponse struct {
Error string `json:"error"`
}
func (s *Server) WriteAPIError(w http.ResponseWriter, r *http.Request, status int, message string) {
encoder := json.NewEncoder(w)
apiErr := APIErrorResponse{Error: message}
w.WriteHeader(status)
if err := encoder.Encode(&apiErr); err != nil {
s.ServerLogger.Debugf("Error encoding or writing error response", "remote_ip", r.RemoteAddr, "error", err)
}
}