Skip to content
Merged
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ https://habr.com/ru/posts/823682/

# Запуск postgress локально на своей машине разворачиваем в Docker
-- docker pull postgres
-- docker run --name=calculation-db -e POSTGRES_PASSWORD='qwerty' -p 5436:5432 -d --rm postgress
-- docker run --name=calculation-db -e POSTGRES_PASSWORD='qwerty' -p 5436:5432 -d --rm postgres
// если нужны файлы миграции(не нужно они созданы)
-- migrate create -ext sql -dir ./schema -seq init
// поднять файлы миграции
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ require (
)

require (
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/fsnotify/fsnotify v1.8.0 // indirect
github.com/gin-gonic/gin v1.10.0
github.com/go-viper/mapstructure/v2 v2.2.1 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQ
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/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M=
Expand Down
2 changes: 1 addition & 1 deletion internal/entity/user/user.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package Calculation

type User struct {
Id int `json:"-"`
Id int `json:"-" db:"id"`
Name string `json:"name" binding:"required"`
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
Expand Down
51 changes: 37 additions & 14 deletions internal/handler/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,6 @@ import (
"github.com/gin-gonic/gin"
)

func (h *Handler) signIn(w *gin.Context) {

}

// @Summary SignUp
// @Tags auth
// @Description create account
Expand Down Expand Up @@ -41,16 +37,43 @@ func (h *Handler) signUp(c *gin.Context) {
"id": id,
})

// err := r.ParseForm()
// if err != nil {
// http.Error(w, "Error parsing form", http.StatusBadRequest)
// return
// }
// username := r.FormValue("username")
// password := r.FormValue("password")
// fmt.Print(username, password)
// w.Header().Set("Content-Type", "text/plain")
// fmt.Fprintf(w, "Received username: %s have %s pass", username, password)
}

type singInInput struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}

// @Summary SignIn
// @Tags auth
// @Description login
// @ID login
// @Accept json
// @Produce json
// @Param input body signInInput true "credentials"
// @Success 200 {string} string "token"
// @Failure 400,404 {object} errorResponse
// @Failure 500 {object} errorResponse
// @Failure default {object} errorResponse
// @Router /auth/sign-in [post]
func (h *Handler) signIn(c *gin.Context) {
var input singInInput

if err := c.BindJSON(&input); err != nil {
newErrorResponse(c, http.StatusBadRequest, err.Error())
return
}

token, err := h.services.Autorization.GenerateToken(input.Username, input.Password)

if err != nil {
newErrorResponse(c, http.StatusInternalServerError, err.Error())
return
}

c.JSON(http.StatusOK, map[string]interface{}{
"token": token,
})
}

func (h *Handler) logout(w *gin.Context) {
Expand Down
2 changes: 0 additions & 2 deletions internal/handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ func NewHandler(services *service.Service) *Handler {
return &Handler{services: services}
}

// @FIX-ME
// GIN Есть вопрос стоит ли использовать фреймворк gin для работы с http или пользоваться нативом
func (h *Handler) InitRoutes() *gin.Engine {
router := gin.New()

Expand Down
8 changes: 8 additions & 0 deletions repository/auth_postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,11 @@ func (r *AuthPostgres) CreateUser(user Calculation.User) (int, error) {

return id, nil
}

func (r *AuthPostgres) GetUser(username, password string) (Calculation.User, error) {
var user Calculation.User
query := fmt.Sprintf("SELECT id FROM %s WHERE username=$1 AND password_hash=$2", usersTable)
err := r.db.Get(&user, query, username, password)

return user, err
}
1 change: 1 addition & 0 deletions repository/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (

type Autorization interface {
CreateUser(user Calculation.User) (int, error)
GetUser(username, password string) (Calculation.User, error)
}

type Repository struct {
Expand Down
28 changes: 27 additions & 1 deletion service/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,22 @@ import (
"calculation-service/repository"
"crypto/sha1"
"fmt"
"time"

"github.com/dgrijalva/jwt-go"
)

const (
salt = "asjdhaskdhqwhejkqwhe123123hhhrjqwehqjw"
salt = "asjdhaskdhqwhejkqwhe123123hhhrjqwehqjw"
tokenTTL = 12 * time.Hour
signingKey = "werwerwerwerwerwerwr"
)

type tokenClaims struct {
jwt.StandardClaims
UserId int `json:"user_id"`
}

type AuthService struct {
repo repository.Autorization
}
Expand All @@ -25,6 +35,22 @@ func (s *AuthService) CreateUser(user Calculation.User) (int, error) {
return s.repo.CreateUser(user)
}

func (s *AuthService) GenerateToken(username, password string) (string, error) {
user, err := s.repo.GetUser(username, generatePasswordHash(password))
if err != nil {
return "", err
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, &tokenClaims{
jwt.StandardClaims{
ExpiresAt: time.Now().Add(tokenTTL).Unix(),
IssuedAt: time.Now().Unix(),
},
user.Id,
})

return token.SignedString([]byte(signingKey))
}

func generatePasswordHash(password string) string {
hash := sha1.New()
hash.Write([]byte(password))
Expand Down
1 change: 1 addition & 0 deletions service/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

type Autorization interface {
CreateUser(user Calculation.User) (int, error)
GenerateToken(username, password string) (string, error)
}

type Service struct {
Expand Down