+
Skip to content

Bugfixinorderlogic #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 19 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions .github/workflows/golangci-lint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
name: golangci-lint
on:
push:
branches:
- master
- main
pull_request:

permissions:
contents: read
# Optional: allow read access to pull request. Use with `only-new-issues` option.
# pull-requests: read

jobs:
golangci:
name: lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: '1.20'
cache: false
- name: golangci-lint
uses: golangci/golangci-lint-action@v3
with:
# Require: The version of golangci-lint to use.
# When `install-mode` is `binary` (default) the value can be v1.2 or v1.2.3 or `latest` to use the latest version.
# When `install-mode` is `goinstall` the value can be v1.2.3, `latest`, or the hash of a commit.
version: v1.53

# Optional: working directory, useful for monorepos
# working-directory: somedir

# Optional: golangci-lint command line arguments.
#
# Note: by default the `.golangci.yml` file should be at the root of the repository.
# The location of the configuration file can be changed by using `--config=`
# args: --timeout=30m --config=/my/path/.golangci.yml --issues-exit-code=0

# Optional: show only new issues if it's a pull request. The default value is `false`.
# only-new-issues: true

# Optional: if set to true then the all caching functionality will be complete disabled,
# takes precedence over all other caching options.
# skip-cache: true

# Optional: if set to true then the action don't cache or restore ~/go/pkg.
# skip-pkg-cache: true

# Optional: if set to true then the action don't cache or restore ~/.cache/go-build.
# skip-build-cache: true

# Optional:The mode to install golangci-lint. It can be 'binary' or 'goinstall'.
# install-mode: "goinstall"
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,4 @@ vendor/
# IDEs directories
.idea
.vscode
cmd/gophermart/migrations
44 changes: 44 additions & 0 deletions cmd/gophermart/flag.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package main

import (
"flag"
"os"
)

type FlagVar struct {
runAddr string
databaseURI string
acuralSystemAddress string
migrationsDir string
}

func NewFlagVarStruct() *FlagVar {
return &FlagVar{}
}
func (f *FlagVar) parseFlags() error {
//postgresql://postgres:docker@localhost:5432/asd?sslmode=disable
// как аргумент -a со значением :8080 по умолчанию
// парсим переданные серверу аргументы в зарегистрированные переменные
flag.StringVar(&f.runAddr, "a", "localhost:8080", "address and port to run server")
flag.StringVar(&f.databaseURI, "d", "", "database connection address")
flag.StringVar(&f.acuralSystemAddress, "r", "", "address of the accrual system")
flag.StringVar(&f.migrationsDir, "m", "", "migrations to db")
flag.Parse()

if envRunAddr, ok := os.LookupEnv("RUN_ADDRESS"); ok {
f.runAddr = envRunAddr
}

if envDatabaseURI, ok := os.LookupEnv("DATABASE_URI"); ok {
f.databaseURI = envDatabaseURI
}

if envAcuralSystemAddress, ok := os.LookupEnv("ACCRUAL_SYSTEM_ADDRESS"); ok {
f.acuralSystemAddress = envAcuralSystemAddress
}

if envMigrationsDir, ok := os.LookupEnv("MIGRATIONS_DIR"); ok {
f.migrationsDir = envMigrationsDir
}
return nil
}
37 changes: 36 additions & 1 deletion cmd/gophermart/main.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,38 @@
package main

func main() {}
import (
"context"
"log"
"net/http"

"github.com/MlDenis/internal/gofermart/auth/cache"
"github.com/MlDenis/internal/gofermart/handlers"
"github.com/MlDenis/internal/gofermart/storage"
)

func main() {
flagStruct := NewFlagVarStruct()
err := flagStruct.parseFlags()
if err != nil {
log.Fatal(err)
}
if err := run(flagStruct); err != nil {
log.Fatalln(err)
}
}
func run(flagStruct *FlagVar) error {

ctx := context.Background()
memStorageInterface, postgresDB, err := storage.NewStorage(ctx, flagStruct.migrationsDir, flagStruct.databaseURI)
if err != nil {
log.Fatal("Error in create storage: ", err)
}
if postgresDB != nil {
defer postgresDB.Close()
}
JWTForSession := cache.NewDataJWT()
newHandStruct := handlers.HandlerNew(memStorageInterface, JWTForSession)
router := handlers.Router(ctx, newHandStruct)
log.Println("Running server on: ", flagStruct.runAddr)
return http.ListenAndServe(flagStruct.runAddr, router)
}
28 changes: 28 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
module github.com/MlDenis

go 1.20

require (
github.com/go-chi/chi/v5 v5.0.10
github.com/golang-jwt/jwt/v4 v4.4.2
github.com/golang-migrate/migrate/v4 v4.16.2
github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa
github.com/jackc/pgx/v5 v5.4.3
github.com/sirupsen/logrus v1.9.3
)

require (
github.com/go-chi/chi v1.5.4 // indirect
github.com/golang-migrate/migrate v3.5.4+incompatible // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
github.com/jackc/puddle/v2 v2.2.1 // indirect
github.com/lib/pq v1.10.2 // indirect
go.uber.org/atomic v1.7.0 // indirect
golang.org/x/crypto v0.9.0 // indirect
golang.org/x/sync v0.2.0 // indirect
golang.org/x/sys v0.8.0 // indirect
golang.org/x/text v0.9.0 // indirect
)
48 changes: 48 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-chi/chi v1.5.4 h1:QHdzF2szwjqVV4wmByUnTcsbIg7UGaQ0tPF2t5GcAIs=
github.com/go-chi/chi v1.5.4/go.mod h1:uaf8YgoFazUOkPBG7fxPftUylNumIev9awIWOENIuEg=
github.com/go-chi/chi/v5 v5.0.10 h1:rLz5avzKpjqxrYwXNfmjkrYYXOyLJd37pz53UFHC6vk=
github.com/go-chi/chi/v5 v5.0.10/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/golang-jwt/jwt/v4 v4.4.2 h1:rcc4lwaZgFMCZ5jxF9ABolDcIHdBytAFgqFPbSJQAYs=
github.com/golang-jwt/jwt/v4 v4.4.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
github.com/golang-migrate/migrate v3.5.4+incompatible h1:R7OzwvCJTCgwapPCiX6DyBiu2czIUMDCB118gFTKTUA=
github.com/golang-migrate/migrate v3.5.4+incompatible/go.mod h1:IsVUlFN5puWOmXrqjgGUfIRIbU7mr8oNBE2tyERd9Wk=
github.com/golang-migrate/migrate/v4 v4.16.2 h1:8coYbMKUyInrFk1lfGfRovTLAW7PhWp8qQDT2iKfuoA=
github.com/golang-migrate/migrate/v4 v4.16.2/go.mod h1:pfcJX4nPHaVdc5nmdCikFBWtm+UBpiZjRNNsyBbp0/o=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=
github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa h1:s+4MhCQ6YrzisK6hFJUX53drDT4UsSW3DEhKn0ifuHw=
github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa/go.mod h1:a/s9Lp5W7n/DD0VrVoyJ00FbP2ytTPDVOivvn2bMlds=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.4.3 h1:cxFyXhxlvAifxnkKKdlxv8XqUf59tDlYjnV5YYfsJJY=
github.com/jackc/pgx/v5 v5.4.3/go.mod h1:Ig06C2Vu0t5qXC60W8sqIthScaEnFvojjj9dSljmHRA=
github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk=
github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/lib/pq v1.10.2 h1:AqzbZs4ZoCBp+GtejcpCpcxM3zlSMx29dXbUSeVtJb8=
github.com/lib/pq v1.10.2/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw=
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
golang.org/x/crypto v0.9.0 h1:LF6fAI+IutBocDJ2OT0Q1g8plpYljMZ4+lty+dsqw3g=
golang.org/x/crypto v0.9.0/go.mod h1:yrmDGqONDYtNj3tH8X9dzUun2m2lzPa9ngI6/RUPGR0=
golang.org/x/sync v0.2.0 h1:PUR+T4wwASmuSTYdKjYHI5TD22Wy5ogLU5qZCOLxBrI=
golang.org/x/sync v0.2.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
38 changes: 38 additions & 0 deletions internal/gofermart/auth/cache/cache.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package cache

import (
"sync"

"github.com/MlDenis/internal/gofermart/models"
"github.com/MlDenis/pkg"
)

// структура где будут хранится токены в оперативной памяти
type DataJWT struct {
data map[string]string
mu sync.RWMutex
}

func NewDataJWT() *DataJWT {
return &DataJWT{
data: map[string]string{},
}
}

// добавляем токен в нашу структуру
func (userJWT *DataJWT) AddToken(userData *models.UserData) {
userJWT.mu.Lock()
defer userJWT.mu.Unlock()
userJWT.data[userData.Token] = userData.Login

}

// получаем токен(для проверки авторизации)
func (userJWT *DataJWT) GetToken(userData *models.UserData) error {
login, ok := userJWT.data[userData.Token]
if !ok {
return pkg.TokenNotExist
}
userData.Login = login
return nil
}
18 changes: 18 additions & 0 deletions internal/gofermart/auth/hashpassword.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package auth

import (
"crypto/hmac"
"crypto/sha256"
"fmt"
)

const SECRET_KEY = "secret"

// хэшируем пароль для последующей ей записи в бд
func HashPassword(data string) (hash string) {
key := []byte(SECRET_KEY)
h := hmac.New(sha256.New, key)
h.Write([]byte(data))
hash = fmt.Sprintf("%x", h.Sum(nil))
return hash
}
33 changes: 33 additions & 0 deletions internal/gofermart/auth/jwt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package auth

import (
"time"

"github.com/golang-jwt/jwt/v4"
)

// токен будет жить 12 часов
const TOKEN_EXP = time.Hour * 12

// структура для нашего токена, можно добавить условия при необходимости
type Claims struct {
jwt.RegisteredClaims
Username string `json:"username"`
}

// создаем токен
func CreateJwtToken(loginUser string) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, Claims{
RegisteredClaims: jwt.RegisteredClaims{
// когда создан токен
ExpiresAt: jwt.NewNumericDate(time.Now().Add(TOKEN_EXP)),
},
// собственное утверждение
Username: loginUser,
})
tokenString, err := token.SignedString([]byte(SECRET_KEY))
if err != nil {
return "", err
}
return tokenString, err
}
Loading
点击 这是indexloc提供的php浏览器服务,不要输入任何密码和下载