From 73b524d203c2a392cd07fe16ce6ad264566e8628 Mon Sep 17 00:00:00 2001 From: nquidox Date: Sat, 3 Jan 2026 15:25:31 +0300 Subject: [PATCH] initial --- .gitignore | 2 + Dockerfile | 19 ++++ config.env | 1 + docs/docs.go | 196 +++++++++++++++++++++++++++++++++++++++++ docs/swagger.json | 170 +++++++++++++++++++++++++++++++++++ docs/swagger.yaml | 109 +++++++++++++++++++++++ go.mod | 57 ++++++++++++ go.sum | 177 +++++++++++++++++++++++++++++++++++++ main.go | 32 +++++++ src/auth/controller.go | 130 +++++++++++++++++++++++++++ src/auth/dto.go | 13 +++ src/auth/handler.go | 29 ++++++ src/auth/model.go | 19 ++++ src/auth/repository.go | 143 ++++++++++++++++++++++++++++++ src/auth/service.go | 105 ++++++++++++++++++++++ src/config/config.go | 20 +++++ src/server/handler.go | 42 +++++++++ src/storage/handler.go | 15 ++++ 18 files changed, 1279 insertions(+) create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 config.env create mode 100644 docs/docs.go create mode 100644 docs/swagger.json create mode 100644 docs/swagger.yaml create mode 100644 go.mod create mode 100644 go.sum create mode 100644 main.go create mode 100644 src/auth/controller.go create mode 100644 src/auth/dto.go create mode 100644 src/auth/handler.go create mode 100644 src/auth/model.go create mode 100644 src/auth/repository.go create mode 100644 src/auth/service.go create mode 100644 src/config/config.go create mode 100644 src/server/handler.go create mode 100644 src/storage/handler.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0eee5c7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.idea +storage.db diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..c7511de --- /dev/null +++ b/Dockerfile @@ -0,0 +1,19 @@ +FROM golang:1.25.5-alpine3.23 AS builder + +RUN apk add --no-cache gcc musl-dev + +WORKDIR /app +COPY go.mod go.sum ./ +RUN go mod download +COPY . . +RUN CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags="-s -w" -o main + + +FROM alpine:3.23 + +COPY --from=builder /app/main /usr/local/bin/app + + +RUN chmod +x /usr/local/bin/app + +ENTRYPOINT ["app"] \ No newline at end of file diff --git a/config.env b/config.env new file mode 100644 index 0000000..90e7f71 --- /dev/null +++ b/config.env @@ -0,0 +1 @@ +ADDRESS=0.0.0.0:8080 diff --git a/docs/docs.go b/docs/docs.go new file mode 100644 index 0000000..65adf60 --- /dev/null +++ b/docs/docs.go @@ -0,0 +1,196 @@ +// Package docs Code generated by swaggo/swag. DO NOT EDIT +package docs + +import "github.com/swaggo/swag" + +const docTemplate = `{ + "schemes": {{ marshal .Schemes }}, + "swagger": "2.0", + "info": { + "description": "{{escape .Description}}", + "title": "{{.Title}}", + "contact": {}, + "version": "{{.Version}}" + }, + "host": "{{.Host}}", + "basePath": "{{.BasePath}}", + "paths": { + "/auth/login": { + "post": { + "description": "Логин. Принимает пару юзернейм+пароль.", + "consumes": [ + "application/json" + ], + "tags": [ + "Auth" + ], + "summary": "Логин", + "parameters": [ + { + "description": "логин", + "name": "login", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/auth.loginDTO" + } + } + ], + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "Bad Request" + }, + "500": { + "description": "Internal Server Error" + } + } + } + }, + "/auth/logout": { + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Логаут. Принимает токен авторизации в заголовке \"Authorization\"", + "tags": [ + "Auth" + ], + "summary": "Логаут", + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "Bad Request" + }, + "500": { + "description": "Internal Server Error" + } + } + } + }, + "/auth/me": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Информация о пользователе. Выдается по токену сессии. Без поля пароль.", + "tags": [ + "Auth" + ], + "summary": "Информация о пользователе", + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "Bad Request" + }, + "500": { + "description": "Internal Server Error" + } + } + } + }, + "/auth/register": { + "post": { + "description": "Регистрация", + "consumes": [ + "application/json" + ], + "tags": [ + "Auth" + ], + "summary": "Регистрация", + "parameters": [ + { + "description": "Регистрация", + "name": "register", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/auth.user" + } + } + ], + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "Bad Request" + }, + "500": { + "description": "Internal Server Error" + } + } + } + } + }, + "definitions": { + "auth.loginDTO": { + "type": "object", + "properties": { + "login": { + "type": "string" + }, + "password": { + "type": "string" + } + } + }, + "auth.user": { + "type": "object", + "properties": { + "email": { + "type": "string" + }, + "name": { + "type": "string" + }, + "password": { + "type": "string" + }, + "surname": { + "type": "string" + }, + "username": { + "type": "string" + } + } + } + }, + "securityDefinitions": { + "ApiKeyAuth": { + "description": "Введите \"token\" для аутентификации", + "type": "apiKey", + "name": "Authorization", + "in": "header" + } + } +}` + +// SwaggerInfo holds exported Swagger Info so clients can modify it +var SwaggerInfo = &swag.Spec{ + Version: "1.0.0", + Host: "", + BasePath: "/api", + Schemes: []string{}, + Title: "Mobile Example API", + Description: "", + InfoInstanceName: "swagger", + SwaggerTemplate: docTemplate, + LeftDelim: "{{", + RightDelim: "}}", +} + +func init() { + swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo) +} diff --git a/docs/swagger.json b/docs/swagger.json new file mode 100644 index 0000000..73beef9 --- /dev/null +++ b/docs/swagger.json @@ -0,0 +1,170 @@ +{ + "swagger": "2.0", + "info": { + "title": "Mobile Example API", + "contact": {}, + "version": "1.0.0" + }, + "basePath": "/api", + "paths": { + "/auth/login": { + "post": { + "description": "Логин. Принимает пару юзернейм+пароль.", + "consumes": [ + "application/json" + ], + "tags": [ + "Auth" + ], + "summary": "Логин", + "parameters": [ + { + "description": "логин", + "name": "login", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/auth.loginDTO" + } + } + ], + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "Bad Request" + }, + "500": { + "description": "Internal Server Error" + } + } + } + }, + "/auth/logout": { + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Логаут. Принимает токен авторизации в заголовке \"Authorization\"", + "tags": [ + "Auth" + ], + "summary": "Логаут", + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "Bad Request" + }, + "500": { + "description": "Internal Server Error" + } + } + } + }, + "/auth/me": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Информация о пользователе. Выдается по токену сессии. Без поля пароль.", + "tags": [ + "Auth" + ], + "summary": "Информация о пользователе", + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "Bad Request" + }, + "500": { + "description": "Internal Server Error" + } + } + } + }, + "/auth/register": { + "post": { + "description": "Регистрация", + "consumes": [ + "application/json" + ], + "tags": [ + "Auth" + ], + "summary": "Регистрация", + "parameters": [ + { + "description": "Регистрация", + "name": "register", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/auth.user" + } + } + ], + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "Bad Request" + }, + "500": { + "description": "Internal Server Error" + } + } + } + } + }, + "definitions": { + "auth.loginDTO": { + "type": "object", + "properties": { + "login": { + "type": "string" + }, + "password": { + "type": "string" + } + } + }, + "auth.user": { + "type": "object", + "properties": { + "email": { + "type": "string" + }, + "name": { + "type": "string" + }, + "password": { + "type": "string" + }, + "surname": { + "type": "string" + }, + "username": { + "type": "string" + } + } + } + }, + "securityDefinitions": { + "ApiKeyAuth": { + "description": "Введите \"token\" для аутентификации", + "type": "apiKey", + "name": "Authorization", + "in": "header" + } + } +} \ No newline at end of file diff --git a/docs/swagger.yaml b/docs/swagger.yaml new file mode 100644 index 0000000..a7a8874 --- /dev/null +++ b/docs/swagger.yaml @@ -0,0 +1,109 @@ +basePath: /api +definitions: + auth.loginDTO: + properties: + login: + type: string + password: + type: string + type: object + auth.user: + properties: + email: + type: string + name: + type: string + password: + type: string + surname: + type: string + username: + type: string + type: object +info: + contact: {} + title: Mobile Example API + version: 1.0.0 +paths: + /auth/login: + post: + consumes: + - application/json + description: Логин. Принимает пару юзернейм+пароль. + parameters: + - description: логин + in: body + name: login + required: true + schema: + $ref: '#/definitions/auth.loginDTO' + responses: + "200": + description: OK + "400": + description: Bad Request + "500": + description: Internal Server Error + summary: Логин + tags: + - Auth + /auth/logout: + post: + description: Логаут. Принимает токен авторизации в заголовке "Authorization" + responses: + "200": + description: OK + "400": + description: Bad Request + "500": + description: Internal Server Error + security: + - ApiKeyAuth: [] + summary: Логаут + tags: + - Auth + /auth/me: + get: + description: Информация о пользователе. Выдается по токену сессии. Без поля + пароль. + responses: + "200": + description: OK + "400": + description: Bad Request + "500": + description: Internal Server Error + security: + - ApiKeyAuth: [] + summary: Информация о пользователе + tags: + - Auth + /auth/register: + post: + consumes: + - application/json + description: Регистрация + parameters: + - description: Регистрация + in: body + name: register + required: true + schema: + $ref: '#/definitions/auth.user' + responses: + "200": + description: OK + "400": + description: Bad Request + "500": + description: Internal Server Error + summary: Регистрация + tags: + - Auth +securityDefinitions: + ApiKeyAuth: + description: Введите "token" для аутентификации + in: header + name: Authorization + type: apiKey +swagger: "2.0" diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..503ece3 --- /dev/null +++ b/go.mod @@ -0,0 +1,57 @@ +module mobile-api-example + +go 1.25.5 + +require ( + github.com/gin-gonic/gin v1.11.0 + github.com/google/uuid v1.6.0 + github.com/mattn/go-sqlite3 v1.14.33 + github.com/swaggo/files v1.0.1 + github.com/swaggo/gin-swagger v1.6.1 + github.com/swaggo/swag v1.16.6 +) + +require ( + github.com/KyleBanks/depth v1.2.1 // indirect + github.com/PuerkitoBio/purell v1.1.1 // indirect + github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect + github.com/bytedance/gopkg v0.1.3 // indirect + github.com/bytedance/sonic v1.14.2 // indirect + github.com/bytedance/sonic/loader v0.4.0 // indirect + github.com/cloudwego/base64x v0.1.6 // indirect + github.com/gabriel-vasile/mimetype v1.4.12 // indirect + github.com/gin-contrib/sse v1.1.0 // indirect + github.com/go-openapi/jsonpointer v0.19.5 // indirect + github.com/go-openapi/jsonreference v0.19.6 // indirect + github.com/go-openapi/spec v0.20.4 // indirect + github.com/go-openapi/swag v0.19.15 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.30.1 // indirect + github.com/goccy/go-json v0.10.5 // indirect + github.com/goccy/go-yaml v1.19.1 // indirect + github.com/josharian/intern v1.0.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.3.0 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/mailru/easyjson v0.7.6 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.2.4 // indirect + github.com/quic-go/qpack v0.6.0 // indirect + github.com/quic-go/quic-go v0.58.0 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.3.1 // indirect + go.uber.org/mock v0.6.0 // indirect + golang.org/x/arch v0.23.0 // indirect + golang.org/x/crypto v0.46.0 // indirect + golang.org/x/mod v0.30.0 // indirect + golang.org/x/net v0.48.0 // indirect + golang.org/x/sync v0.19.0 // indirect + golang.org/x/sys v0.39.0 // indirect + golang.org/x/text v0.32.0 // indirect + golang.org/x/tools v0.39.0 // indirect + google.golang.org/protobuf v1.36.11 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..5760369 --- /dev/null +++ b/go.sum @@ -0,0 +1,177 @@ +github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc= +github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE= +github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI= +github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= +github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M= +github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= +github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M= +github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM= +github.com/bytedance/sonic v1.14.2 h1:k1twIoe97C1DtYUo+fZQy865IuHia4PR5RPiuGPPIIE= +github.com/bytedance/sonic v1.14.2/go.mod h1:T80iDELeHiHKSc0C9tubFygiuXoGzrkjKzX2quAx980= +github.com/bytedance/sonic/loader v0.4.0 h1:olZ7lEqcxtZygCK9EKYKADnpQoYkRQxaeY2NYzevs+o= +github.com/bytedance/sonic/loader v0.4.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo= +github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= +github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= +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/gin-contrib/gzip v0.0.6 h1:NjcunTcGAj5CO1gn4N8jHOSIeRFHIbn51z6K+xaN4d4= +github.com/gin-contrib/gzip v0.0.6/go.mod h1:QOJlmV2xmayAjkNS2Y8NQsMneuRShOU/kjovCXNuzzk= +github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w= +github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM= +github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk= +github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls= +github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= +github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY= +github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= +github.com/go-openapi/jsonreference v0.19.6 h1:UBIxjkht+AWIgYzCDSv2GN+E/togfwXUJFRTWhl2Jjs= +github.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns= +github.com/go-openapi/spec v0.20.4 h1:O8hJrt0UMnhHcluhIdUgCLRWyM2x7QkBXRvOs7m+O1M= +github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7FOEWeq8I= +github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= +github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM= +github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= +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/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= +github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/goccy/go-yaml v1.19.1 h1:3rG3+v8pkhRqoQ/88NYNMHYVGYztCOCIZ7UQhu7H+NE= +github.com/goccy/go-yaml v1.19.1/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= +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/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +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/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= +github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +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/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA= +github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +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-sqlite3 v1.14.33 h1:A5blZ5ulQo2AtayQ9/limgHEkFreKj1Dv226a1K73s0= +github.com/mattn/go-sqlite3 v1.14.33/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= +github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +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/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= +github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= +github.com/quic-go/quic-go v0.58.0 h1:ggY2pvZaVdB9EyojxL1p+5mptkuHyX5MOSv4dgWF4Ug= +github.com/quic-go/quic-go v0.58.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU= +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/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +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/swaggo/files v1.0.1 h1:J1bVJ4XHZNq0I46UU90611i9/YzdrF7x92oX1ig5IdE= +github.com/swaggo/files v1.0.1/go.mod h1:0qXmMNH6sXNf+73t65aKeB+ApmgxdnkQzVTAj2uaMUg= +github.com/swaggo/gin-swagger v1.6.1 h1:Ri06G4gc9N4t4k8hekMigJ9zKTFSlqj/9paAQCQs7cY= +github.com/swaggo/gin-swagger v1.6.1/go.mod h1:LQ+hJStHakCWRiK/YNYtJOu4mR2FP+pxLnILT/qNiTw= +github.com/swaggo/swag v1.16.6 h1:qBNcx53ZaX+M5dxVyTrgQ0PJ/ACK+NzhwcbieTt+9yI= +github.com/swaggo/swag v1.16.6/go.mod h1:ngP2etMK5a0P3QBizic5MEwpRmluJZPHjXcMoj4Xesg= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY= +github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= +go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= +golang.org/x/arch v0.23.0 h1:lKF64A2jF6Zd8L0knGltUnegD62JMFBiCPBmQpToHhg= +golang.org/x/arch v0.23.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU= +golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.30.0 h1:fDEXFVZ/fmCKProc/yAXXUijritrDzahmwwefnjoPFk= +golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU= +golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +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-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= +golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= +golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ= +golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/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.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/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= diff --git a/main.go b/main.go new file mode 100644 index 0000000..13bd24e --- /dev/null +++ b/main.go @@ -0,0 +1,32 @@ +package main + +import ( + _ "mobile-api-example/docs" + "mobile-api-example/src/auth" + "mobile-api-example/src/config" + "mobile-api-example/src/server" + "mobile-api-example/src/storage" +) + +// @Title Mobile Example API +// @Version 1.0.0 +// @BasePath /api +// @securityDefinitions.apikey ApiKeyAuth +// @In header +// @Name Authorization +// @Description Введите "token" для аутентификации +func main() { + c := config.NewConfig() + + db, err := storage.Connect() + if err != nil { + panic(err) + } + defer db.Close() + + srv := server.NewServer() + + auth.NewHandler(db, srv.BaseGroup) + + srv.Run(c.Address) +} diff --git a/src/auth/controller.go b/src/auth/controller.go new file mode 100644 index 0000000..7b0d6b6 --- /dev/null +++ b/src/auth/controller.go @@ -0,0 +1,130 @@ +package auth + +import ( + "net/http" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" +) + +type controller struct { + service *service +} + +func newController(s *service) *controller { + return &controller{ + service: s, + } +} + +func (h Handler) registerRoutes(r *gin.RouterGroup) { + authGroup := r.Group("/auth") + + authGroup.POST("/login", h.controller.login) + authGroup.POST("/logout", h.controller.logout) + + authGroup.POST("/register", h.controller.register) + authGroup.GET("/me", h.controller.me) +} + +// @Summary Логин +// @Description Логин. Принимает пару юзернейм+пароль. +// @Tags Auth +// @Accept json +// @Param login body loginDTO true "логин" +// @Success 200 +// @Failure 400 +// @Failure 500 +// @Router /auth/login [post] +func (co *controller) login(c *gin.Context) { + var login loginDTO + if err := c.ShouldBindJSON(&login); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + token, err := co.service.login(login) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.Header("Authorization", "Bearer "+token) + + c.Status(http.StatusOK) +} + +// @Summary Логаут +// @Description Логаут. Принимает токен авторизации в заголовке "Authorization" +// @Security ApiKeyAuth +// @Tags Auth +// @Success 200 +// @Failure 400 +// @Failure 500 +// @Router /auth/logout [post] +func (co *controller) logout(c *gin.Context) { + token := c.GetHeader("Authorization") + + err := uuid.Validate(token) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + if err := co.service.logout(token); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.Status(http.StatusOK) +} + +// @Summary Регистрация +// @Description Регистрация +// @Tags Auth +// @Accept json +// @Param register body user true "Регистрация" +// @Success 200 +// @Failure 400 +// @Failure 500 +// @Router /auth/register [post] +func (co *controller) register(c *gin.Context) { + var registerUser user + if err := c.ShouldBindJSON(®isterUser); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + if err := co.service.register(registerUser); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.Status(http.StatusOK) +} + +// @Summary Информация о пользователе +// @Description Информация о пользователе. Выдается по токену сессии. Без поля пароль. +// @Security ApiKeyAuth +// @Tags Auth +// @Success 200 +// @Failure 400 +// @Failure 500 +// @Router /auth/me [get] +func (co *controller) me(c *gin.Context) { + token := c.GetHeader("Authorization") + + err := uuid.Validate(token) + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()}) + return + } + + me, err := co.service.me(token) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusOK, me) +} diff --git a/src/auth/dto.go b/src/auth/dto.go new file mode 100644 index 0000000..c90c608 --- /dev/null +++ b/src/auth/dto.go @@ -0,0 +1,13 @@ +package auth + +type loginDTO struct { + Login string `json:"login"` + Password string `json:"password"` +} + +type meDTO struct { + Username string `json:"username"` + Name string `json:"name"` + Surname string `json:"surname"` + Email string `json:"email"` +} diff --git a/src/auth/handler.go b/src/auth/handler.go new file mode 100644 index 0000000..a5d3baf --- /dev/null +++ b/src/auth/handler.go @@ -0,0 +1,29 @@ +package auth + +import ( + "database/sql" + + "github.com/gin-gonic/gin" +) + +type Handler struct { + repo Repository + service *service + controller *controller +} + +func NewHandler(db *sql.DB, baseGroup *gin.RouterGroup) *Handler { + r := newRepo(db) + s := newService(r) + c := newController(s) + + h := &Handler{ + repo: r, + service: s, + controller: c, + } + + h.registerRoutes(baseGroup) + + return h +} diff --git a/src/auth/model.go b/src/auth/model.go new file mode 100644 index 0000000..4c2d1ad --- /dev/null +++ b/src/auth/model.go @@ -0,0 +1,19 @@ +package auth + +import "database/sql" + +type user struct { + Id int `json:"-"` + Username string `json:"username"` + Password string `json:"password"` + Name string `json:"name"` + Surname string `json:"surname"` + Email string `json:"email"` +} + +type session struct { + id int + userId int + token string + deletedAt sql.NullTime +} diff --git a/src/auth/repository.go b/src/auth/repository.go new file mode 100644 index 0000000..fa1e79d --- /dev/null +++ b/src/auth/repository.go @@ -0,0 +1,143 @@ +package auth + +import ( + "database/sql" + "fmt" +) + +type repo struct { + db *sql.DB +} + +func newRepo(db *sql.DB) *repo { + usersTable := ` + CREATE TABLE IF NOT EXISTS users ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + username VARCHAR(255) UNIQUE NOT NULL, + password VARCHAR(255) NOT NULL, + name VARCHAR(255) NOT NULL, + surname VARCHAR(255) NOT NULL, + email VARCHAR(255) NOT NULL + ); + ` + _, err := db.Exec(usersTable) + if err != nil { + panic(err) + } + + sessionsTable := ` + CREATE TABLE IF NOT EXISTS sessions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + userId INTEGER NOT NULL, + token VARCHAR(36) UNIQUE NOT NULL, + deletedAt TEXT DEFAULT NULL + ); + ` + _, err = db.Exec(sessionsTable) + if err != nil { + panic(err) + } + + return &repo{ + db: db, + } +} + +type Repository interface { + register(u user) error + getUser(login string) (user, error) + me(token string) (user, error) + + sessions +} + +type sessions interface { + newSession(s session) error + getSessionToken(userId int) (string, error) + getUserIdBySessionToken(token string) (int, error) + deleteSession(userId int) error +} + +func (r *repo) register(u user) error { + q := `INSERT INTO users (username, password, name, surname, email) VALUES (?, ?, ?, ?, ?)` + _, err := r.db.Exec(q, u.Username, u.Password, u.Name, u.Surname, u.Email) + if err != nil { + return err + } + + return nil +} + +func (r *repo) getUser(login string) (user, error) { + q := `SELECT id, username, password FROM users WHERE username = ?` + + var u user + err := r.db.QueryRow(q, login).Scan(&u.Id, &u.Username, &u.Password) + if err != nil { + return user{}, err + } + return u, nil +} + +func (r *repo) me(token string) (user, error) { + userId, err := r.getUserIdBySessionToken(token) + fmt.Println("kek1", userId, err) + if err != nil { + return user{}, err + } + + q := `SELECT username, name, surname, email FROM users WHERE id = ?` + var u user + err = r.db.QueryRow(q, userId).Scan(&u.Username, &u.Name, &u.Surname, &u.Email) + fmt.Println("kek2", u, err) + if err != nil { + return user{}, err + } + + return u, nil +} + +func (r *repo) newSession(s session) error { + q := `INSERT INTO sessions (userId, token, deletedAt) VALUES (?, ?, ?)` + + _, err := r.db.Exec(q, s.userId, s.token, s.deletedAt) + if err != nil { + return err + } + + return nil +} + +func (r *repo) getSessionToken(userId int) (string, error) { + q := `SELECT token FROM sessions WHERE userId = ? AND deletedAt IS NULL` + + var token string + err := r.db.QueryRow(q, userId).Scan(&token) + if err != nil { + return "", err + } + + return token, nil +} + +func (r *repo) getUserIdBySessionToken(token string) (int, error) { + q := `SELECT userId FROM sessions WHERE token = ? AND deletedAt IS NULL` + + var userId int + err := r.db.QueryRow(q, token).Scan(&userId) + if err != nil { + return -1, err + } + + return userId, nil +} + +func (r *repo) deleteSession(userId int) error { + q := `DELETE FROM sessions WHERE userId = ?` + + _, err := r.db.Exec(q, userId) + if err != nil { + return err + } + return nil +} diff --git a/src/auth/service.go b/src/auth/service.go new file mode 100644 index 0000000..fe045aa --- /dev/null +++ b/src/auth/service.go @@ -0,0 +1,105 @@ +package auth + +import ( + "database/sql" + "errors" + "fmt" + "time" + + "github.com/google/uuid" +) + +type service struct { + repo Repository +} + +func newService(repo Repository) *service { + return &service{ + repo: repo, + } +} + +func (s *service) register(u user) error { + if u.Username == "" { + return errors.New("login required") + } + + if u.Password == "" { + return errors.New("password required") + } + + return s.repo.register(u) +} + +func (s *service) login(login loginDTO) (string, error) { + getUser, err := s.repo.getUser(login.Login) + if err != nil { + return "", err + } + + fmt.Println(getUser) + + if getUser.Password != login.Password { + return "", errors.New("wrong password") + } + + token, err := s.repo.getSessionToken(getUser.Id) + if errors.Is(err, sql.ErrNoRows) || token == "" { + fmt.Println("session not found, creating new one") + newToken, err := s._createNewSession(getUser.Id) + if err != nil { + return "", err + } + + return newToken, nil + + } else if err != nil { + return "", err + } + + return token, nil +} + +func (s *service) logout(token string) error { + userId, err := s.repo.getUserIdBySessionToken(token) + if err != nil { + return err + } + + if userId < 0 { + return errors.New("invalid token") + } + + return s.repo.deleteSession(userId) +} + +func (s *service) _createNewSession(userId int) (string, error) { + token := uuid.NewString() + newSession := session{ + userId: userId, + token: token, + deletedAt: sql.NullTime{ + Time: time.Time{}, + Valid: false, + }, + } + + if err := s.repo.newSession(newSession); err != nil { + return "", err + } + return token, nil +} + +func (s *service) me(token string) (meDTO, error) { + usr, err := s.repo.me(token) + if err != nil { + return meDTO{}, err + } + + return meDTO{ + Username: usr.Username, + Name: usr.Name, + Surname: usr.Surname, + Email: usr.Email, + }, nil +} diff --git a/src/config/config.go b/src/config/config.go new file mode 100644 index 0000000..6357b3b --- /dev/null +++ b/src/config/config.go @@ -0,0 +1,20 @@ +package config + +import "os" + +type Config struct { + Address string +} + +func NewConfig() *Config { + return &Config{ + Address: getEnv("ADDRESS", "0.0.0.0:18080"), + } +} + +func getEnv(key, fallback string) string { + if value, ok := os.LookupEnv(key); ok { + return value + } + return fallback +} diff --git a/src/server/handler.go b/src/server/handler.go new file mode 100644 index 0000000..9c8d7af --- /dev/null +++ b/src/server/handler.go @@ -0,0 +1,42 @@ +package server + +import ( + "github.com/gin-gonic/gin" + swaggerFiles "github.com/swaggo/files" + ginSwagger "github.com/swaggo/gin-swagger" +) + +type Server struct { + engine *gin.Engine + BaseGroup *gin.RouterGroup +} + +func NewServer() *Server { + engine := gin.Default() + + engine.Handle("GET", "/", func(c *gin.Context) { + c.JSON(200, gin.H{ + "message": "It works!", + }) + }) + + engine.Handle("GET", "/about", func(c *gin.Context) { + c.JSON(200, gin.H{ + "about": "This is an example server", + "version": "1.0.0", + }) + }) + + engine.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) + + return &Server{ + engine: engine, + BaseGroup: engine.Group("/api"), + } +} + +func (s *Server) Run(address string) { + if err := s.engine.Run(address); err != nil { + panic(err) + } +} diff --git a/src/storage/handler.go b/src/storage/handler.go new file mode 100644 index 0000000..7089646 --- /dev/null +++ b/src/storage/handler.go @@ -0,0 +1,15 @@ +package storage + +import ( + "database/sql" + + _ "github.com/mattn/go-sqlite3" +) + +func Connect() (*sql.DB, error) { + db, err := sql.Open("sqlite3", "./storage.db") + if err != nil { + return nil, err + } + return db, nil +}