Compare commits

..

No commits in common. "b3362d4a664d975997162d4bc3a9f888de687dd7" and "155deb889cc5d0dc30f8bff6e499a9606c239415" have entirely different histories.

9 changed files with 26 additions and 111 deletions

View File

@ -32,7 +32,7 @@ func main() {
r := gin.Default()
docs.SwaggerInfo.BasePath = "/api"
r.Use(cors.New(cors.Config{
AllowOrigins: []string{"http://localhost:5173"},
AllowOrigins: []string{"*"},
AllowMethods: []string{"GET", "DELETE", "PUT", "PATCH", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Type"},
ExposeHeaders: []string{"Content-Length"},
@ -44,7 +44,6 @@ func main() {
api := r.Group("/api")
{
api.GET("/ping", handlers.PingGet)
api.GET("/authping", middleware.AuthMiddleware(), handlers.PingGet)
userRoutes := api.Group("/user")
{
userRoutes.POST("/register", handlers.UserRegister)

View File

@ -1,5 +0,0 @@
package consts
const (
COOKIE_SESSION = "session"
)

View File

@ -53,6 +53,5 @@ func Connect() *gorm.DB {
gormDB.AutoMigrate(&Transfer{})
gormDB.AutoMigrate(&User{})
gormDB.AutoMigrate(&Type{})
gormDB.AutoMigrate(&Session{})
return newUDB
}

View File

@ -1,10 +0,0 @@
package db
import "time"
type Session struct {
ID string `gorm:"primaryKey"`
UserID uint
User *User
ExpireAt time.Time
}

View File

@ -3,7 +3,6 @@ package handlers
import (
"log"
"git.qowevisa.me/Qowevisa/fin-check-api/consts"
"git.qowevisa.me/Qowevisa/fin-check-api/db"
"git.qowevisa.me/Qowevisa/fin-check-api/tokens"
"git.qowevisa.me/Qowevisa/fin-check-api/types"
@ -48,11 +47,9 @@ func UserRegister(c *gin.Context) {
}
token1 = token
}
c.SetCookie(consts.COOKIE_SESSION, token1.Val, 3600, "/", "localhost", false, true)
acc := types.Account{
ID: dbUser.ID,
Token: token1.Val,
Username: dbUser.Username,
}
c.JSON(200, acc)
}
@ -85,7 +82,7 @@ func UserLogin(c *gin.Context) {
return
}
if foundUser.ID == 0 {
c.JSON(400, types.ErrorResponse{Message: "Credentials are incorrect"})
c.JSON(500, types.ErrorResponse{Message: "Credentials are incorrect"})
return
}
var token1 *tokens.Token
@ -100,13 +97,9 @@ func UserLogin(c *gin.Context) {
}
token1 = token
}
c.SetCookie(consts.COOKIE_SESSION, token1.Val, 3600, "/", "localhost", false, true)
acc := types.Account{
ID: foundUser.ID,
Token: token1.Val,
Username: dbUser.Username,
}
c.JSON(200, acc)
}
func isSessionTokenForUserInvalid(userID uint) {}

View File

@ -1,11 +1,8 @@
package middleware
import (
"errors"
"log"
"net/http"
"strings"
"git.qowevisa.me/Qowevisa/fin-check-api/consts"
"git.qowevisa.me/Qowevisa/fin-check-api/tokens"
"git.qowevisa.me/Qowevisa/fin-check-api/types"
"github.com/gin-gonic/gin"
@ -14,25 +11,31 @@ import (
// Passes UserID with `c.Set("UserID")` as it gets id from token
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
token, err := c.Cookie(consts.COOKIE_SESSION)
if errors.Is(err, http.ErrNoCookie) {
c.JSON(401, types.ErrorResponse{Message: "Authorization cookie is required"})
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(401, types.ErrorResponse{Message: "Authorization header is required"})
c.Abort()
return
}
if !tokens.ValidateSessionToken(token) {
c.JSON(401, types.ErrorResponse{Message: "Invalid authorization cookie"})
token := authHeader
if strings.Index(token, "Bearer ") == 0 {
token = strings.Split(token, " ")[1]
}
if !tokens.AmIAllowed(token) {
c.JSON(401, types.ErrorResponse{Message: "Token is invalid"})
c.Abort()
return
}
session, err := tokens.GetSession(token)
if err != nil {
log.Printf("ERROR: tokens.GetSession: %v\n", err)
c.JSON(500, types.ErrorResponse{Message: "Server error"})
if userID, err := tokens.GetID(token); err != nil {
c.JSON(401, types.ErrorResponse{Message: "Token is invalid ERR4001"})
c.Abort()
return
} else {
c.Set("UserID", userID)
}
c.Set("UserID", session.UserID)
c.Next()
}

View File

@ -138,7 +138,7 @@ func AddToken(id uint) (*Token, error) {
_, exists := toks.Tokmap[id]
toks.Mu.RUnlock()
if exists {
// return nil, ERROR_ALREADY_HAVE_TOKEN
return nil, ERROR_ALREADY_HAVE_TOKEN
}
val := generateTokenVal()
token := &Token{

View File

@ -1,58 +0,0 @@
package tokens
import (
"crypto/sha256"
"log"
"time"
"git.qowevisa.me/Qowevisa/fin-check-api/db"
)
func getSalt() []byte {
return []byte("w40DJV3v1flySvFdxHWbBSJsIOaakkVs5FG7brq4oi1#nEz2fEZxpUfyBwkkww7f")
}
func CreateSessionFromToken(token string, userID uint) error {
salt := getSalt()
sessionID := sha256.New().Sum(append(salt, []byte(token)...))
dbc := db.Connect()
session := &db.Session{
ID: string(sessionID),
UserID: userID,
ExpireAt: time.Now().Add(time.Hour),
}
if err := dbc.Create(session).Error; err != nil {
return err
}
return nil
}
func ValidateSessionToken(token string) bool {
salt := getSalt()
sessionID := sha256.New().Sum(append(salt, []byte(token)...))
dbc := db.Connect()
session := &db.Session{}
if err := dbc.Find(session, sessionID).Error; err != nil {
log.Printf("DBERROR: %v\n", err)
return false
}
if session.ID == "" {
return false
}
if session.ExpireAt.Unix() < time.Now().Unix() {
dbc.Delete(session)
return false
}
return session.ID != ""
}
func GetSession(token string) (*db.Session, error) {
salt := getSalt()
sessionID := sha256.New().Sum(append(salt, []byte(token)...))
dbc := db.Connect()
session := &db.Session{}
if err := dbc.Find(session, sessionID).Error; err != nil {
return nil, err
}
return session, nil
}

View File

@ -11,8 +11,7 @@ type User struct {
// User Account
type Account struct {
ID uint `json:"id" example:"1"`
Token string `json:"token" example:"Fvs-MnxiEs5dnqMp2mSDIJigPbiIUs6Snk1xxiqPmUc"`
Username string `json:"username" example:"testUser"`
Token string `json:"token" example:"Fvs-MnxiEs5dnqMp2mSDIJigPbiIUs6Snk1xxiqPmUc="`
}
type Message struct {
@ -75,8 +74,3 @@ type DbPayment struct {
Note string `json:"not" example:"I'm a teapot"`
Date time.Time `json:"date" example:"29/11/2001 12:00"`
}
type Session struct {
ID string `json:"id"`
UserID uint `json:"user_id" example:"1"`
}