Compare commits
No commits in common. "e02a05c2545180f66bc3c6c3f643b4129ef648fa" and "7b8f7c3e8e76edb593a4d123f9bcf8a716890650" have entirely different histories.
e02a05c254
...
7b8f7c3e8e
1
go.mod
1
go.mod
@ -17,7 +17,6 @@ require (
|
|||||||
github.com/go-playground/locales v0.14.0 // indirect
|
github.com/go-playground/locales v0.14.0 // indirect
|
||||||
github.com/go-playground/universal-translator v0.18.0 // indirect
|
github.com/go-playground/universal-translator v0.18.0 // indirect
|
||||||
github.com/go-playground/validator/v10 v10.11.0 // indirect
|
github.com/go-playground/validator/v10 v10.11.0 // indirect
|
||||||
github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
|
|
||||||
github.com/golang/protobuf v1.5.2 // indirect
|
github.com/golang/protobuf v1.5.2 // indirect
|
||||||
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
|
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
|
||||||
github.com/jackc/pgconn v1.12.1 // indirect
|
github.com/jackc/pgconn v1.12.1 // indirect
|
||||||
|
2
go.sum
2
go.sum
@ -32,8 +32,6 @@ github.com/go-resty/resty/v2 v2.7.0/go.mod h1:9PWDzw47qPphMRFfhsyk0NnSgvluHcljSM
|
|||||||
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
|
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
|
||||||
github.com/gofrs/uuid v4.0.0+incompatible h1:1SD/1F5pU8p29ybwgQSwpQk+mwdRrXCYuPhW6m+TnJw=
|
github.com/gofrs/uuid v4.0.0+incompatible h1:1SD/1F5pU8p29ybwgQSwpQk+mwdRrXCYuPhW6m+TnJw=
|
||||||
github.com/gofrs/uuid v4.0.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
|
github.com/gofrs/uuid v4.0.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
|
||||||
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
|
|
||||||
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
|
|
||||||
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
|
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
|
||||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||||
github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw=
|
github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw=
|
||||||
|
@ -3,26 +3,17 @@ package photosapi
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/golang-jwt/jwt"
|
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Errors
|
// Errors
|
||||||
var (
|
var (
|
||||||
ErrAccountExists = errors.New("account exists")
|
ErrAccountExists = errors.New("account exists")
|
||||||
ErrAccountAuth = errors.New("login or password incorrect")
|
ErrAccountAuth = errors.New("login or password incorrect")
|
||||||
ErrAccountTokenMissing = errors.New("token missing")
|
|
||||||
ErrAccountTokenInvalid = errors.New("token invalid")
|
|
||||||
)
|
|
||||||
|
|
||||||
// Const
|
|
||||||
const (
|
|
||||||
TOKEN = 1
|
|
||||||
REFRESH_TOKEN = 2
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Model
|
// Model
|
||||||
@ -54,36 +45,7 @@ type LoginRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type LoginResponse struct {
|
type LoginResponse struct {
|
||||||
Token string `json:"token"`
|
Token string `json:"token"`
|
||||||
RefreshToken string `json:"refresh_token"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// JWT
|
|
||||||
type JWT struct {
|
|
||||||
Type int `json:"typ"`
|
|
||||||
ExpireAt int64 `json:"exp"`
|
|
||||||
AccountId uint32 `json:"acc"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *JWT) Valid() error {
|
|
||||||
return jwt.MapClaims{
|
|
||||||
"exp": float64(j.ExpireAt),
|
|
||||||
}.Valid()
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewJWTToken(accountId uint32) *JWT {
|
|
||||||
return &JWT{
|
|
||||||
Type: TOKEN,
|
|
||||||
ExpireAt: time.Now().Add(time.Minute * 15).Unix(),
|
|
||||||
AccountId: accountId,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
func NewJWTRefreshToken(accountId uint32) *JWT {
|
|
||||||
return &JWT{
|
|
||||||
Type: REFRESH_TOKEN,
|
|
||||||
ExpireAt: time.Now().Add(time.Hour * 24).Unix(),
|
|
||||||
AccountId: accountId,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) Signup(c *gin.Context) {
|
func (s *Service) Signup(c *gin.Context) {
|
||||||
@ -111,89 +73,41 @@ func (s *Service) Signup(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) Login(c *gin.Context) {
|
func (s *Service) Login(c *gin.Context) {
|
||||||
var loginRequest *LoginRequest
|
var account *LoginRequest
|
||||||
|
|
||||||
if c.BindJSON(&loginRequest) != nil {
|
if c.BindJSON(&account) != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
account := &Account{}
|
session, err := NewSession(s.DB, account.Login, account.Password)
|
||||||
if err := s.DB.Where(
|
|
||||||
"login = ?",
|
|
||||||
loginRequest.Login,
|
|
||||||
).First(account).Error; err != nil {
|
|
||||||
c.AbortWithError(http.StatusNotFound, ErrAccountAuth)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := bcrypt.CompareHashAndPassword(account.Password, []byte(loginRequest.Password)); err != nil {
|
|
||||||
c.AbortWithError(http.StatusNotFound, ErrAccountAuth)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
token, err := jwt.NewWithClaims(&jwt.SigningMethodEd25519{}, NewJWTToken(account.ID)).SignedString(s.SessionKey)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.AbortWithError(http.StatusInternalServerError, err)
|
if errors.Is(err, gorm.ErrRecordNotFound) || errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
|
||||||
|
c.AbortWithError(http.StatusNotFound, ErrAccountAuth)
|
||||||
|
} else {
|
||||||
|
c.AbortWithError(http.StatusInternalServerError, err)
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
refresh_token, err := jwt.NewWithClaims(&jwt.SigningMethodEd25519{}, NewJWTRefreshToken(account.ID)).SignedString(s.SessionKey)
|
c.JSON(http.StatusOK, LoginResponse{session.Token})
|
||||||
if err != nil {
|
|
||||||
c.AbortWithError(http.StatusInternalServerError, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, LoginResponse{
|
|
||||||
Token: token,
|
|
||||||
RefreshToken: refresh_token,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) LoginRefresh(c *gin.Context) {
|
func (s *Service) Logout(c *gin.Context) {
|
||||||
auth := strings.Split(c.GetHeader("Authorization"), " ")
|
res := s.DB.Where("token = ?", c.GetString("token")).Delete(&Session{})
|
||||||
if len(auth) != 2 {
|
if res.Error != nil {
|
||||||
c.AbortWithError(http.StatusForbidden, ErrAccountTokenMissing)
|
c.AbortWithError(http.StatusInternalServerError, res.Error)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if res.RowsAffected == 0 {
|
||||||
if auth[0] != "Bearer" {
|
c.AbortWithError(http.StatusNotFound, ErrSessionNotFound)
|
||||||
c.AbortWithError(http.StatusForbidden, ErrAccountTokenMissing)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
c.Status(http.StatusNoContent)
|
||||||
var claims JWT
|
|
||||||
refresh_token, err := jwt.ParseWithClaims(auth[1], &claims, func(t *jwt.Token) (interface{}, error) {
|
|
||||||
if _, ok := t.Method.(*jwt.SigningMethodEd25519); !ok {
|
|
||||||
return nil, ErrAccountTokenInvalid
|
|
||||||
}
|
|
||||||
return s.SessionKeyValidation, nil
|
|
||||||
})
|
|
||||||
|
|
||||||
if err != nil || !refresh_token.Valid || claims.Type != REFRESH_TOKEN {
|
|
||||||
c.AbortWithError(http.StatusForbidden, ErrAccountTokenInvalid)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
token, err := jwt.NewWithClaims(&jwt.SigningMethodEd25519{}, NewJWTToken(claims.AccountId)).SignedString(s.SessionKey)
|
|
||||||
if err != nil {
|
|
||||||
c.AbortWithError(http.StatusInternalServerError, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
new_refresh_token, err := jwt.NewWithClaims(&jwt.SigningMethodEd25519{}, NewJWTRefreshToken(claims.AccountId)).SignedString(s.SessionKey)
|
|
||||||
if err != nil {
|
|
||||||
c.AbortWithError(http.StatusInternalServerError, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, LoginResponse{
|
|
||||||
Token: token,
|
|
||||||
RefreshToken: new_refresh_token,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) AccountInit() {
|
func (s *Service) AccountInit() {
|
||||||
ac := s.Gin.Group("/account")
|
ac := s.Gin.Group("/account")
|
||||||
ac.POST("/signup", s.Signup)
|
ac.POST("/signup", s.Signup)
|
||||||
ac.POST("/login", s.Login)
|
ac.POST("/login", s.Login)
|
||||||
ac.GET("/refresh", s.LoginRefresh)
|
ac.GET("/logout", s.RequireAuthToken, s.Logout)
|
||||||
}
|
}
|
||||||
|
@ -33,6 +33,7 @@ func (d *DBConfig) DSN() string {
|
|||||||
func (s *Service) Migrate() {
|
func (s *Service) Migrate() {
|
||||||
tx := s.DB
|
tx := s.DB
|
||||||
tx.AutoMigrate(&Account{})
|
tx.AutoMigrate(&Account{})
|
||||||
|
tx.AutoMigrate(&Session{})
|
||||||
tx.AutoMigrate(&File{})
|
tx.AutoMigrate(&File{})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -257,8 +257,8 @@ var (
|
|||||||
// }
|
// }
|
||||||
|
|
||||||
func (s *Service) FileInit() {
|
func (s *Service) FileInit() {
|
||||||
// file := s.Gin.Group("/file")
|
file := s.Gin.Group("/file")
|
||||||
// file.Use(s.RequireSession)
|
file.Use(s.RequireSession)
|
||||||
// file.POST("", s.FileCreate)
|
// file.POST("", s.FileCreate)
|
||||||
// file.HEAD("/:checksum", s.FileExists)
|
// file.HEAD("/:checksum", s.FileExists)
|
||||||
// file.GET("/:checksum", s.FileGet)
|
// file.GET("/:checksum", s.FileGet)
|
||||||
|
@ -2,13 +2,11 @@ package photosapi
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/ed25519"
|
|
||||||
"errors"
|
"errors"
|
||||||
"math/rand"
|
"math/rand"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
"path/filepath"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
@ -21,15 +19,13 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Service struct {
|
type Service struct {
|
||||||
Gin *gin.Engine
|
Gin *gin.Engine
|
||||||
DB *gorm.DB
|
DB *gorm.DB
|
||||||
Config *ServiceConfig
|
Config *ServiceConfig
|
||||||
StorageTmp *Storage
|
StorageTmp *Storage
|
||||||
StorageUpload *Storage
|
StorageUpload *Storage
|
||||||
LogOk *Logger
|
LogOk *Logger
|
||||||
LogErr *Logger
|
LogErr *Logger
|
||||||
SessionKey ed25519.PrivateKey
|
|
||||||
SessionKeyValidation ed25519.PublicKey
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type ServiceConfig struct {
|
type ServiceConfig struct {
|
||||||
@ -38,34 +34,14 @@ type ServiceConfig struct {
|
|||||||
StorePath string
|
StorePath string
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetOrGenerateKey(storePath string) ed25519.PrivateKey {
|
|
||||||
p := filepath.Join(storePath, "photo.key")
|
|
||||||
key, err := os.ReadFile(p)
|
|
||||||
if errors.Is(err, os.ErrNotExist) {
|
|
||||||
_, key, err = ed25519.GenerateKey(nil)
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
err = os.WriteFile(p, key, 0600)
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return key
|
|
||||||
}
|
|
||||||
|
|
||||||
func New(config *ServiceConfig) *Service {
|
func New(config *ServiceConfig) *Service {
|
||||||
key := GetOrGenerateKey(config.StorePath)
|
|
||||||
pubKey := key.Public().(ed25519.PublicKey)
|
|
||||||
return &Service{
|
return &Service{
|
||||||
Gin: gin.New(),
|
Gin: gin.New(),
|
||||||
Config: config,
|
Config: config,
|
||||||
StorageTmp: NewStorage(config.StorePath, "tmp"),
|
StorageTmp: NewStorage(config.StorePath, "tmp"),
|
||||||
StorageUpload: NewStorage(config.StorePath, "upload"),
|
StorageUpload: NewStorage(config.StorePath, "upload"),
|
||||||
LogOk: &Logger{os.Stdout, "Photos"},
|
LogOk: &Logger{os.Stdout, "Photos"},
|
||||||
LogErr: &Logger{os.Stderr, "Photos"},
|
LogErr: &Logger{os.Stderr, "Photos"},
|
||||||
SessionKey: key,
|
|
||||||
SessionKeyValidation: pubKey,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -102,6 +78,7 @@ func (s *Service) Run() error {
|
|||||||
s.PrepareStore()
|
s.PrepareStore()
|
||||||
s.SetupRoutes()
|
s.SetupRoutes()
|
||||||
s.SetupDB()
|
s.SetupDB()
|
||||||
|
go s.SessionCleaner()
|
||||||
|
|
||||||
srv := &http.Server{
|
srv := &http.Server{
|
||||||
Addr: s.Config.Listen,
|
Addr: s.Config.Listen,
|
||||||
|
Loading…
x
Reference in New Issue
Block a user