feat(authentication): Added authentication controller & JWTMiddleware
This commit is contained in:
@@ -0,0 +1,246 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gofrs/uuid/v5"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"medad.fun/internal/config"
|
||||
"medad.fun/internal/database"
|
||||
"medad.fun/internal/database/models"
|
||||
)
|
||||
|
||||
type registerBody struct {
|
||||
Name string `json:"name" validate:"required"`
|
||||
Username string `json:"username" validate:"required_without_all=Phone Email,omitempty,unique=user&username,min=4,max=24"`
|
||||
Email string `json:"email" validate:"required_without_all=Phone Username,omitempty,unique=user&email,email"`
|
||||
Phone string `json:"phone" validate:"required_without_all=Email Username,omitempty,unique=user&phone,min=11,max=11"`
|
||||
Password string `json:"password" validate:"required"`
|
||||
}
|
||||
|
||||
type loginBody struct {
|
||||
Login string `json:"login" validate:"required"`
|
||||
Password string `json:"password" validate:"required"`
|
||||
}
|
||||
|
||||
func Register(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to read request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
var userReq registerBody
|
||||
if err := json.Unmarshal(body, &userReq); err != nil {
|
||||
http.Error(w, "Invalid JSON format", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
userReq.Email = strings.ToLower(userReq.Email)
|
||||
userReq.Username = strings.ToLower(userReq.Username)
|
||||
|
||||
// rows, err := database.Pool.Query(r.Context(), "SELECT id, name FROM my_table")
|
||||
// if err != nil {
|
||||
// http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
// return
|
||||
// }
|
||||
// defer rows.Close()
|
||||
|
||||
// var data []map[string]interface{}
|
||||
// for rows.Next() {
|
||||
// var id int
|
||||
// var name string
|
||||
// if err := rows.Scan(&id, &name); err != nil {
|
||||
// http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
// return
|
||||
// }
|
||||
// data = append(data, map[string]interface{}{
|
||||
// "id": id,
|
||||
// "name": name,
|
||||
// })
|
||||
// }
|
||||
|
||||
// validate input
|
||||
validate := validator.New()
|
||||
validate.RegisterValidation("unique", NewUniqueValidator(database.Pool))
|
||||
err = validate.Struct(userReq)
|
||||
if err != nil {
|
||||
if started, err := marshalToHTTPWriterError(w, err, "validation_error|user", http.StatusUnprocessableEntity); err != nil {
|
||||
if !started {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// // unique validation
|
||||
// var count int
|
||||
// if err := database.Pool.QueryRow(r.Context(), `SELECT count(id) FROM "user" WHERE username = $1 OR email = $2 OR phone = $3 LIMIT 1`,
|
||||
// strings.ToLower(userReq.Username),
|
||||
// strings.ToLower(userReq.Email),
|
||||
// userReq.Phone,
|
||||
// ).Scan(&count); err != nil || count > 0 {
|
||||
// if started, err := marshalToHTTPWriterError(w, validator.ValidationErrors{validator.FieldError}, "validation_error|user", http.StatusUnprocessableEntity); err != nil {
|
||||
// if !started {
|
||||
// http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
// }
|
||||
// return
|
||||
// }
|
||||
// return
|
||||
// }
|
||||
|
||||
// register user
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(userReq.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
user := models.UserModel{}
|
||||
insert_err := database.Pool.QueryRow(r.Context(), `INSERT INTO "user"(id, name, username, email, phone, password) VALUES ($1, $2, $3, $4, $5, $6) RETURNING *`,
|
||||
uuid.Must(uuid.NewV4()),
|
||||
userReq.Name,
|
||||
strings.ToLower(userReq.Username),
|
||||
strings.ToLower(userReq.Email),
|
||||
userReq.Phone,
|
||||
hashedPassword,
|
||||
).Scan(
|
||||
&user.ID,
|
||||
&user.Name,
|
||||
&user.Username,
|
||||
&user.Email,
|
||||
&user.Phone,
|
||||
&user.Password,
|
||||
&user.CreatedAt,
|
||||
&user.UpdatedAt,
|
||||
)
|
||||
if insert_err != nil {
|
||||
log.Print(insert_err)
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Sign JWT
|
||||
claims := jwt.MapClaims{
|
||||
"user_id": user.ID,
|
||||
"is_admin": false,
|
||||
"exp": time.Now().Add(time.Hour * 24 * 90).Unix(), // Token expires in 90 days
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
|
||||
signedToken, err := token.SignedString([]byte(config.CachedConfig.JWTSecret))
|
||||
if err != nil {
|
||||
log.Fatalf("Error signing token: %v", err)
|
||||
}
|
||||
|
||||
if started, err := marshalToHTTPWriter(w, map[string]any{"token": signedToken, "user": user}, "register|user"); err != nil {
|
||||
if !started {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func Login(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to read request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
var req loginBody
|
||||
if err := json.Unmarshal(body, &req); err != nil {
|
||||
http.Error(w, "Invalid JSON format", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// validate input
|
||||
validate := validator.New()
|
||||
err = validate.Struct(req)
|
||||
if err != nil {
|
||||
if started, err := marshalToHTTPWriterError(w, err, "validation_error|user", http.StatusUnprocessableEntity); err != nil {
|
||||
if !started {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
rows, err := database.Pool.Query(r.Context(), `SELECT id, password FROM "user" WHERE username = $1 OR email = $1 OR phone = $1 LIMIT 3`, strings.ToLower(req.Login))
|
||||
if err != nil {
|
||||
log.Print(err)
|
||||
if started, err := marshalToHTTPWriterError(w, nil, "not_found|user", http.StatusNotFound); err != nil {
|
||||
if !started {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var token string
|
||||
for rows.Next() {
|
||||
var id string
|
||||
var password string
|
||||
if err := rows.Scan(&id, &password); err != nil {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if bcrypt.CompareHashAndPassword([]byte(password), []byte(req.Password)) == nil {
|
||||
// Sign JWT
|
||||
claims := jwt.MapClaims{
|
||||
"user_id": id,
|
||||
"is_admin": false,
|
||||
"exp": time.Now().Add(time.Hour * 24 * 90).Unix(), // Token expires in 90 days
|
||||
}
|
||||
|
||||
token_claim := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
|
||||
token, err = token_claim.SignedString([]byte(config.CachedConfig.JWTSecret))
|
||||
if err != nil {
|
||||
log.Fatalf("Error signing token: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// no user matched
|
||||
if token == "" {
|
||||
if started, err := marshalToHTTPWriterError(w, nil, "not_found|user", http.StatusNotFound); err != nil {
|
||||
if !started {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if started, err := marshalToHTTPWriter(w, map[string]any{"token": token}, "login|user"); err != nil {
|
||||
if !started {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user