Skip to content
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

Регистрация и авторизация #29

Open
wants to merge 34 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
bd87e15
Регистрация и авторизация
Azcarot Feb 16, 2024
17222a7
main
Azcarot Feb 16, 2024
0039fe9
Правка регистрации
Azcarot Feb 16, 2024
e30d00e
О да
Azcarot Feb 16, 2024
a34d140
токен при регистрации
Azcarot Feb 16, 2024
8535e63
Order
Azcarot Feb 18, 2024
e3e7751
Order
Azcarot Feb 18, 2024
376ac79
лун
Azcarot Feb 18, 2024
c23f2f4
Конфликт заказов
Azcarot Feb 18, 2024
2a621e4
Новый хендлер + запрос к сервису
Azcarot Feb 19, 2024
27b9b32
sadsa
Azcarot Feb 19, 2024
e11cebd
sfdf
Azcarot Feb 19, 2024
5cef85d
получение заказов
Azcarot Feb 19, 2024
a8b677f
выавыа
Azcarot Feb 19, 2024
5d7acad
Ошибки в sql
Azcarot Feb 19, 2024
3173cea
ПЫВПВЫПВЫПВЫП
Azcarot Feb 19, 2024
10ddad6
test
Azcarot Feb 19, 2024
7e0c1c3
string
Azcarot Feb 19, 2024
6f3df37
string
Azcarot Feb 19, 2024
f0f3cb1
string
Azcarot Feb 19, 2024
4dae0f6
все хендлеры
Azcarot Feb 21, 2024
b2e6002
сброс бд
Azcarot Feb 21, 2024
871191e
Ошибки в SQL
Azcarot Feb 21, 2024
e5d5233
Обновил базу
Azcarot Feb 22, 2024
15d71f7
расчет в копейках
Azcarot Feb 22, 2024
efaa7c0
Тикер на запрос
Azcarot Feb 22, 2024
bf77cec
sad
Azcarot Feb 22, 2024
4797233
убрал заголовок
Azcarot Feb 22, 2024
f27c7f8
убрал заголовок
Azcarot Feb 22, 2024
88093bc
лог
Azcarot Feb 22, 2024
c60efce
лог
Azcarot Feb 22, 2024
08fe7ca
лог
Azcarot Feb 22, 2024
289b172
списание
Azcarot Feb 22, 2024
6195a66
Починка снятия баланса
Azcarot Feb 22, 2024
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
30 changes: 29 additions & 1 deletion cmd/gophermart/main.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,31 @@
package main

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

"github.com/Azcarot/GopherMarketProject/internal/router"
"github.com/Azcarot/GopherMarketProject/internal/storage"
"github.com/Azcarot/GopherMarketProject/internal/utils"
)

func main() {

flag := utils.ParseFlagsAndENV()
if flag.FlagDBAddr != "" {
err := storage.NewConn(flag)
if err != nil {
panic(err)
}
storage.CheckDBConnection(storage.DB)
storage.CreateTablesForGopherStore(storage.DB)
defer storage.DB.Close(context.Background())
}
r := router.MakeRouter(flag)
server := &http.Server{
Addr: flag.FlagAddr,
Handler: r,
}
server.ListenAndServe()

}
16 changes: 16 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
module github.com/Azcarot/GopherMarketProject

go 1.21.4

require (
github.com/caarlos0/env v3.5.0+incompatible // indirect
github.com/go-chi/chi/v5 v5.0.11 // indirect
github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
github.com/jackc/pgx/v5 v5.5.3 // indirect
go.uber.org/multierr v1.10.0 // indirect
go.uber.org/zap v1.26.0 // indirect
golang.org/x/crypto v0.17.0 // indirect
golang.org/x/text v0.14.0 // indirect
)
27 changes: 27 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
github.com/caarlos0/env v3.5.0+incompatible h1:Yy0UN8o9Wtr/jGHZDpCBLpNrzcFLLM2yixi/rBrKyJs=
github.com/caarlos0/env v3.5.0+incompatible/go.mod h1:tdCsowwCzMLdkqRYDlHpZCp2UooDD3MspDBjZ2AD02Y=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-chi/chi/v5 v5.0.11 h1:BnpYbFZ3T3S1WMpD79r7R5ThWX40TaFB7L31Y8xqSwA=
github.com/go-chi/chi/v5 v5.0.11/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
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.5.3 h1:Ces6/M3wbDXYpM8JyyPD57ivTtJACFZJd885pdIaV2s=
github.com/jackc/pgx/v5 v5.5.3/go.mod h1:ez9gk+OAat140fv9ErkZDYFWmXLfV+++K0uAOiwgm1A=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
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/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo=
go.uber.org/zap v1.26.0/go.mod h1:dtElttAiwGvoJ/vj4IwHBS/gXsEu/pZ50mUIRWuG0so=
golang.org/x/crypto v0.17.0 h1:r8bRNjWL3GshPW3gkd+RpvzWrZAwPS49OmTGZ/uhM4k=
golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
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=
5 changes: 5 additions & 0 deletions go.work
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
go 1.21.4

use (
.
)
9 changes: 9 additions & 0 deletions go.work.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
48 changes: 48 additions & 0 deletions internal/handlers/balance.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package handlers

import (
"encoding/json"
"net/http"

"github.com/Azcarot/GopherMarketProject/internal/storage"
)

func GetBalance() http.Handler {
balance := func(res http.ResponseWriter, req *http.Request) {
// var buf bytes.Buffer
token := req.Header.Get("Authorization")
claims, ok := storage.VerifyToken(token)
if !ok {
res.WriteHeader(http.StatusUnauthorized)
return
}
var userData storage.UserData
userData.Login = claims["sub"].(string)
ok, err := storage.CheckUserExists(storage.DB, userData)
if err != nil {
res.WriteHeader(http.StatusInternalServerError)
return
}
if !ok {
res.WriteHeader(http.StatusUnauthorized)
return
}
var balanceData storage.BalanceResponce
balanceData, err = storage.GetUserBalance(storage.DB, userData)
if err != nil {
res.WriteHeader(http.StatusInternalServerError)
return
}
balanceData.Accrual = balanceData.Accrual / 100
balanceData.Withdrawn = balanceData.Withdrawn / 100
result, err := json.Marshal(balanceData)
if err != nil {
res.WriteHeader(http.StatusInternalServerError)
return
}
res.Header().Add("Content-Type", "application/json")
res.WriteHeader(http.StatusOK)
res.Write(result)
}
return http.HandlerFunc(balance)
}
151 changes: 151 additions & 0 deletions internal/handlers/getorders.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
package handlers

import (
"bytes"
"encoding/json"
"net/http"
"strconv"
"sync"
"time"

"github.com/Azcarot/GopherMarketProject/internal/storage"
"github.com/Azcarot/GopherMarketProject/internal/utils"
"github.com/jackc/pgx/v5"
)

func GetOrders() http.Handler {
getorder := func(res http.ResponseWriter, req *http.Request) {
// var buf bytes.Buffer
token := req.Header.Get("Authorization")
claims, ok := storage.VerifyToken(token)
if !ok {
res.WriteHeader(http.StatusUnauthorized)
return
}
var userData storage.UserData
userData.Login = claims["sub"].(string)
ok, err := storage.CheckUserExists(storage.DB, userData)

if err != nil {
res.WriteHeader(http.StatusInternalServerError)
return
}
if !ok {
res.WriteHeader(http.StatusUnauthorized)
return
}
orders, err := storage.GetCustomerOrders(storage.DB, userData.Login)
if err == pgx.ErrNoRows {
res.WriteHeader(http.StatusNoContent)
return
}
if err != nil {
res.WriteHeader(http.StatusInternalServerError)
return
}
result, err := json.Marshal(orders)
if err != nil {
res.WriteHeader(http.StatusInternalServerError)
return
}
res.Header().Add("Content-Type", "application/json")
res.WriteHeader(http.StatusOK)
res.Write(result)

}
return http.HandlerFunc(getorder)
}
func GetOrderData(flag utils.Flags, order uint64) (OrderRequest, error) {
pth := flag.FlagAccrualAddr + "/api/orders/" + strconv.Itoa(int(order))
var b []byte
result := OrderRequest{}
resp, err := http.NewRequest("GET", pth, bytes.NewBuffer(b))
if err != nil {
return result, err
}

var res *http.Response
res, err = CheckStatus(resp)
if err != nil {
return result, err
}
defer res.Body.Close()

var buf bytes.Buffer
// читаем тело запроса
_, err = buf.ReadFrom(res.Body)
if err != nil {
return result, err
}
data := buf.Bytes()

if err = json.Unmarshal(data, &result); err != nil {
return result, err
}
return result, err
}

func CheckStatus(resp *http.Request) (*http.Response, error) {
client := &http.Client{}
res, err := client.Do(resp)
if err != nil {
return res, err
}
if res.StatusCode == http.StatusTooManyRequests {
time.Sleep(time.Duration(1 * time.Second))
res, _ = CheckStatus(resp)

}
return res, err
}

func ActualiseOrders(flag utils.Flags, quit chan struct{}) {
orderNumbers, err := storage.GetUnfinishedOrders(storage.DB)
if err != nil {
time.Sleep(time.Duration(time.Duration(5).Seconds()))
orderNumbers, err = storage.GetUnfinishedOrders(storage.DB)
if err != nil {
return
}
}
var wg sync.WaitGroup
for i, order := range orderNumbers {
ind := i
ord := order
wg.Add(1)
go func(int, uint64) {
defer wg.Done()
orderReq, err := GetOrderData(flag, ord)
if err != nil {
return
}
if (orderReq.Status != "NEW") && (orderReq.Status != "PROCESSING") {
var orderData storage.OrderData
orderData.Accrual = int(orderReq.Accrual * 100)
orderNumber, err := strconv.Atoi(orderReq.OrderNumber)
if err != nil {
return
}
orderData.OrderNumber = uint64(orderNumber)
orderData.State = orderReq.Status
err = storage.UpdateOrder(storage.DB, orderData)
if err != nil {
return
}
if orderData.Accrual > 0 {
_, err := storage.AddBalanceToUser(storage.DB, orderData)
if err != nil {
return
}
}
orderNumbers[ind] = orderNumbers[len(orderNumbers)-1]
orderNumbers = orderNumbers[:len(orderNumbers)-1]
}
if len(orderNumbers) == 0 {
return
}
}(ind, ord)
}
wg.Wait()

}
45 changes: 45 additions & 0 deletions internal/handlers/getwithdrawals.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package handlers

import (
"encoding/json"
"net/http"

"github.com/Azcarot/GopherMarketProject/internal/storage"
)

func GetWithdrawals() http.Handler {
withdraw := func(res http.ResponseWriter, req *http.Request) {
// var buf bytes.Buffer
token := req.Header.Get("Authorization")
claims, ok := storage.VerifyToken(token)
if !ok {
res.WriteHeader(http.StatusUnauthorized)
return
}
var userData storage.UserData
userData.Login = claims["sub"].(string)
ok, err := storage.CheckUserExists(storage.DB, userData)
if err != nil {
res.WriteHeader(http.StatusInternalServerError)
return
}
if !ok {
res.WriteHeader(http.StatusUnauthorized)
return
}
withdrawals, err := storage.GetWithdrawals(storage.DB, userData)
if err != nil {
res.WriteHeader(http.StatusInternalServerError)
return
}
result, err := json.Marshal(withdrawals)
if err != nil {
res.WriteHeader(http.StatusInternalServerError)
return
}
res.Header().Add("Content-Type", "application/json")
res.WriteHeader(http.StatusOK)
res.Write(result)
}
return http.HandlerFunc(withdraw)
}
Loading