mirror of
https://github.com/FJurmanovic/wallet-go-api.git
synced 2026-02-06 06:08:16 +00:00
fixes on structuring
This commit is contained in:
@@ -22,15 +22,15 @@ func NewLoginController(rs *services.UsersService, s *gin.RouterGroup) *LoginCon
|
||||
}
|
||||
|
||||
func (rc *LoginController) Post(c *gin.Context) {
|
||||
loginBody := new(models.LoginModel)
|
||||
if err := c.ShouldBindJSON(&loginBody); err != nil {
|
||||
body := new(models.LoginModel)
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
returnedUser, returnException := rc.UsersService.Login(loginBody)
|
||||
returnedUser, exceptionReturn := rc.UsersService.Login(body)
|
||||
|
||||
if returnException.Message != "" {
|
||||
c.JSON(returnException.StatusCode, returnException)
|
||||
if exceptionReturn.Message != "" {
|
||||
c.JSON(exceptionReturn.StatusCode, exceptionReturn)
|
||||
} else {
|
||||
c.JSON(200, returnedUser)
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"net/http"
|
||||
"wallet-api/pkg/models"
|
||||
"wallet-api/pkg/services"
|
||||
"wallet-api/pkg/utl/common"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
@@ -23,23 +22,18 @@ func NewRegisterController(rs *services.UsersService, s *gin.RouterGroup) *Regis
|
||||
}
|
||||
|
||||
func (rc *RegisterController) Post(c *gin.Context) {
|
||||
registerBody := createUserModel()
|
||||
if err := c.ShouldBindJSON(®isterBody); err != nil {
|
||||
body := new(models.UserModel)
|
||||
body.Init()
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
returnedUser, returnException := rc.UsersService.Create(®isterBody)
|
||||
returnedUser, exceptionReturn := rc.UsersService.Create(body)
|
||||
|
||||
if returnException.Message != "" {
|
||||
c.JSON(returnException.StatusCode, returnException)
|
||||
if exceptionReturn.Message != "" {
|
||||
c.JSON(exceptionReturn.StatusCode, exceptionReturn)
|
||||
} else {
|
||||
c.JSON(200, returnedUser.Payload())
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func createUserModel() models.UserModel {
|
||||
commonModel := common.CreateDbModel()
|
||||
userModel := models.UserModel{CommonModel: commonModel}
|
||||
return userModel
|
||||
}
|
||||
|
||||
@@ -1,7 +1,58 @@
|
||||
package middleware
|
||||
|
||||
import "github.com/gin-gonic/gin"
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"wallet-api/pkg/models"
|
||||
"wallet-api/pkg/utl/configs"
|
||||
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func Auth(c *gin.Context) {
|
||||
exceptionReturn := new(models.ExceptionModel)
|
||||
tokenString := ExtractToken(c)
|
||||
secret := os.Getenv("ACCESS_SECRET")
|
||||
if secret == "" {
|
||||
secret = configs.Secret
|
||||
}
|
||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||
_, ok := token.Method.(*jwt.SigningMethodHMAC)
|
||||
println(ok)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return []byte(secret), nil
|
||||
})
|
||||
if err != nil {
|
||||
exceptionReturn.ErrorCode = "401001"
|
||||
exceptionReturn.StatusCode = 401
|
||||
exceptionReturn.Message = "Invalid token"
|
||||
c.AbortWithStatusJSON(exceptionReturn.StatusCode, exceptionReturn)
|
||||
}
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
if ok && token.Valid {
|
||||
userId, _ := claims["id"].(string)
|
||||
|
||||
authModel := new(models.AuthModel)
|
||||
authModel.Id = userId
|
||||
|
||||
c.Set("auth", authModel)
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
|
||||
func ExtractToken(c *gin.Context) string {
|
||||
bearerToken := c.GetHeader("Authorization")
|
||||
tokenArr := strings.Split(bearerToken, " ")
|
||||
if len(tokenArr) == 2 {
|
||||
bearerCheck := strings.ToLower(tokenArr[0])
|
||||
if bearerCheck == "bearer" {
|
||||
return tokenArr[1]
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -8,3 +8,7 @@ type LoginModel struct {
|
||||
Email string
|
||||
Password string
|
||||
}
|
||||
|
||||
type AuthModel struct {
|
||||
Id string
|
||||
}
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type CommonModel struct {
|
||||
Id string `json:"id" pg:"id"`
|
||||
Id string `json:"id" pg:"id,pk"`
|
||||
DateCreated time.Time `json:"dateCreated" pg:"datecreated"`
|
||||
DateUpdated time.Time `json:"dateUpdated" pg:"dateupdated"`
|
||||
}
|
||||
|
||||
func (cm *CommonModel) Init() {
|
||||
date := time.Now()
|
||||
cm.Id = uuid.NewString()
|
||||
cm.DateCreated = date
|
||||
cm.DateUpdated = date
|
||||
}
|
||||
|
||||
@@ -3,9 +3,9 @@ package models
|
||||
type UserModel struct {
|
||||
tableName struct{} `pg:"users,alias:users"`
|
||||
CommonModel
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Email string `json:"email"`
|
||||
Username string `json:"username" pg:"username"`
|
||||
Password string `json:"password" pg:"password"`
|
||||
Email string `json:"email" pg:"email"`
|
||||
}
|
||||
|
||||
type UserReturnInfoModel struct {
|
||||
@@ -15,11 +15,11 @@ type UserReturnInfoModel struct {
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
func (um *UserModel) Payload() UserReturnInfoModel {
|
||||
payload := UserReturnInfoModel{
|
||||
CommonModel: um.CommonModel,
|
||||
Username: um.Username,
|
||||
Email: um.Email,
|
||||
}
|
||||
func (um *UserModel) Payload() *UserReturnInfoModel {
|
||||
payload := new(UserReturnInfoModel)
|
||||
payload.CommonModel = um.CommonModel
|
||||
payload.Username = um.Username
|
||||
payload.Email = um.Email
|
||||
|
||||
return payload
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"time"
|
||||
"wallet-api/pkg/models"
|
||||
"wallet-api/pkg/utl/common"
|
||||
"wallet-api/pkg/utl/configs"
|
||||
|
||||
jwt "github.com/dgrijalva/jwt-go"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
@@ -16,16 +17,16 @@ type UsersService struct {
|
||||
Db *pg.DB
|
||||
}
|
||||
|
||||
func (us *UsersService) Create(registerBody *models.UserModel) (*models.UserModel, models.ExceptionModel) {
|
||||
var checkModel models.UserModel
|
||||
var exceptionReturn models.ExceptionModel
|
||||
func (us *UsersService) Create(registerBody *models.UserModel) (*models.UserModel, *models.ExceptionModel) {
|
||||
check := new(models.UserModel)
|
||||
exceptionReturn := new(models.ExceptionModel)
|
||||
|
||||
us.Db.Model(&checkModel).Where("? = ?", pg.Ident("username"), registerBody.Username).WhereOr("? = ?", pg.Ident("email"), registerBody.Email).Select()
|
||||
if checkModel.Username != "" || checkModel.Email != "" {
|
||||
us.Db.Model(check).Where("? = ?", pg.Ident("username"), registerBody.Username).WhereOr("? = ?", pg.Ident("email"), registerBody.Email).Select()
|
||||
if check.Username != "" || check.Email != "" {
|
||||
exceptionReturn.Message = "User already exists"
|
||||
exceptionReturn.ErrorCode = "400101"
|
||||
exceptionReturn.StatusCode = 400
|
||||
return &checkModel, exceptionReturn
|
||||
return check, exceptionReturn
|
||||
}
|
||||
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(registerBody.Password), bcrypt.DefaultCost)
|
||||
@@ -43,27 +44,27 @@ func (us *UsersService) Create(registerBody *models.UserModel) (*models.UserMode
|
||||
return registerBody, exceptionReturn
|
||||
}
|
||||
|
||||
func (us *UsersService) Login(loginBody *models.LoginModel) (models.TokenModel, models.ExceptionModel) {
|
||||
var checkModel models.UserModel
|
||||
var exceptionReturn models.ExceptionModel
|
||||
var tokenPayload models.TokenModel
|
||||
func (us *UsersService) Login(loginBody *models.LoginModel) (*models.TokenModel, *models.ExceptionModel) {
|
||||
check := new(models.UserModel)
|
||||
exceptionReturn := new(models.ExceptionModel)
|
||||
tokenPayload := new(models.TokenModel)
|
||||
|
||||
us.Db.Model(&checkModel).Where("? = ?", pg.Ident("email"), loginBody.Email).Select()
|
||||
if checkModel.Email == "" {
|
||||
us.Db.Model(check).Where("? = ?", pg.Ident("email"), loginBody.Email).Select()
|
||||
if check.Email == "" {
|
||||
exceptionReturn.Message = "Email not found"
|
||||
exceptionReturn.ErrorCode = "400103"
|
||||
exceptionReturn.StatusCode = 400
|
||||
return tokenPayload, exceptionReturn
|
||||
}
|
||||
|
||||
if bcrypt.CompareHashAndPassword([]byte(checkModel.Password), []byte(loginBody.Password)) != nil {
|
||||
if bcrypt.CompareHashAndPassword([]byte(check.Password), []byte(loginBody.Password)) != nil {
|
||||
exceptionReturn.Message = "Incorrect password"
|
||||
exceptionReturn.ErrorCode = "400104"
|
||||
exceptionReturn.StatusCode = 400
|
||||
return tokenPayload, exceptionReturn
|
||||
}
|
||||
|
||||
token, err := CreateToken(checkModel)
|
||||
token, err := CreateToken(check)
|
||||
common.CheckError(err)
|
||||
|
||||
tokenPayload.Token = token
|
||||
@@ -71,15 +72,15 @@ func (us *UsersService) Login(loginBody *models.LoginModel) (models.TokenModel,
|
||||
return tokenPayload, exceptionReturn
|
||||
}
|
||||
|
||||
func CreateToken(user models.UserModel) (string, error) {
|
||||
func CreateToken(user *models.UserModel) (string, error) {
|
||||
atClaims := jwt.MapClaims{}
|
||||
atClaims["authorized"] = true
|
||||
atClaims["id"] = user.Id
|
||||
atClaims["exp"] = time.Now().Add(time.Minute * 15).Unix()
|
||||
atClaims["exp"] = time.Now().Add(time.Minute).Unix()
|
||||
|
||||
secret := os.Getenv("ACCESS_SECRET")
|
||||
if secret == "" {
|
||||
secret = "Dond3sta"
|
||||
secret = configs.Secret
|
||||
}
|
||||
|
||||
at := jwt.NewWithClaims(jwt.SigningMethodHS256, atClaims)
|
||||
|
||||
@@ -2,10 +2,6 @@ package common
|
||||
|
||||
import (
|
||||
"log"
|
||||
"time"
|
||||
"wallet-api/pkg/models"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func CheckError(err error) {
|
||||
@@ -13,13 +9,3 @@ func CheckError(err error) {
|
||||
log.Fatalf("Error occured. %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func CreateDbModel() models.CommonModel {
|
||||
date := time.Now()
|
||||
dbModel := models.CommonModel{
|
||||
Id: uuid.NewString(),
|
||||
DateCreated: date,
|
||||
DateUpdated: date,
|
||||
}
|
||||
return dbModel
|
||||
}
|
||||
|
||||
17
pkg/utl/common/embeds.go
Normal file
17
pkg/utl/common/embeds.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/go-pg/pg/v10/orm"
|
||||
)
|
||||
|
||||
func GenerateEmbed(qr *orm.Query, embed string) *orm.Query{
|
||||
if embed != "" {
|
||||
rels := strings.Split(embed, ",")
|
||||
for _, rel := range rels {
|
||||
qr = qr.Relation(rel)
|
||||
}
|
||||
}
|
||||
return qr
|
||||
}
|
||||
@@ -3,4 +3,5 @@ package configs
|
||||
const (
|
||||
Version = "0.0.1"
|
||||
Prefix = "v1"
|
||||
Secret = "Donde4sta"
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user