100 lines
2.5 KiB
Go
100 lines
2.5 KiB
Go
package models
|
|
|
|
import (
|
|
"database/sql"
|
|
"fmt"
|
|
"github.com/golang-jwt/jwt/v5"
|
|
"golang.org/x/crypto/bcrypt"
|
|
"os"
|
|
"time"
|
|
"udemy_httpserver/db"
|
|
)
|
|
|
|
type User struct {
|
|
ID int
|
|
Name string `binding:"required" json:"name"`
|
|
Email string `binding:"required" json:"email"`
|
|
Password string `binding:"required" json:"password"`
|
|
}
|
|
|
|
func (u *User) New() error {
|
|
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
fmt.Println("Something went wrong trying to hash a user password")
|
|
return err
|
|
}
|
|
u.Password = string(hashedPassword)
|
|
|
|
insertQuery := `INSERT INTO users (name, email, password)
|
|
VALUES (?, ?, ?)`
|
|
|
|
_, err = db.Conn.Exec(insertQuery, u.Name, u.Email, u.Password)
|
|
return nil
|
|
}
|
|
|
|
func FindOneByEmail(email string) (*User, error) {
|
|
selectQuery := `SELECT * FROM users WHERE email = ?`
|
|
|
|
dbResponse, err := db.Conn.Query(selectQuery, email)
|
|
defer closeDbConnection(dbResponse)
|
|
if err != nil {
|
|
fmt.Println("Something went wrong trying to find a user")
|
|
return nil, err
|
|
}
|
|
if dbResponse.Next() {
|
|
var user User
|
|
err = dbResponse.Scan(&user.ID, &user.Name, &user.Email, &user.Password)
|
|
if err != nil {
|
|
fmt.Println("Something went wrong parsing the database row")
|
|
return nil, err
|
|
}
|
|
return &user, nil
|
|
}
|
|
return nil, nil
|
|
}
|
|
|
|
func FindOneByID(id int) (*User, error) {
|
|
selectQuery := `SELECT * FROM users WHERE id =?`
|
|
|
|
dbResponse, err := db.Conn.Query(selectQuery, id)
|
|
defer closeDbConnection(dbResponse)
|
|
if err != nil {
|
|
fmt.Println("Something went wrong trying to find a user")
|
|
return nil, err
|
|
}
|
|
if dbResponse.Next() {
|
|
var user User
|
|
err = dbResponse.Scan(&user.ID, &user.Name, &user.Email, &user.Password)
|
|
if err != nil {
|
|
fmt.Println("Something went wrong parsing the database row")
|
|
return nil, err
|
|
}
|
|
return &user, nil
|
|
}
|
|
return nil, nil
|
|
}
|
|
|
|
func (u *User) GetJWToken() (string, error) {
|
|
expirationDelta, err := time.ParseDuration(os.Getenv("AUTH_EXPIRATION"))
|
|
if err != nil {
|
|
fmt.Println("Something went wrong trying to parse AUTH_EXPIRATION env variable")
|
|
return "", err
|
|
}
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
|
"sub": u.ID,
|
|
"exp": time.Now().Add(expirationDelta).Unix(),
|
|
})
|
|
tokenString, err := token.SignedString([]byte(os.Getenv("JWT_SECRET")))
|
|
if err != nil {
|
|
fmt.Println("Something went wrong trying to sign the token")
|
|
return "", err
|
|
}
|
|
return tokenString, nil
|
|
}
|
|
func closeDbConnection(dbResponse *sql.Rows) {
|
|
err := dbResponse.Close()
|
|
if err != nil {
|
|
fmt.Println("Something went wrong closing the database row")
|
|
}
|
|
}
|