2022-05-27 00:12:34 +02:00

200 lines
4.8 KiB
Go

package photosapi
import (
"errors"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
"golang.org/x/crypto/bcrypt"
)
// Errors
var (
ErrAccountExists = errors.New("account exists")
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
type Account struct {
ID uint32 `gorm:"primary_key" json:"-"`
Login string `gorm:"unique;size:64;not null" json:"login"`
Password []byte `gorm:"type:varchar(60);not null" json:"-"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"-"`
}
func NewAccount(login string, password string) *Account {
p, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
return &Account{
Login: login,
Password: p,
}
}
// Service
type SignupRequest struct {
Login string `json:"login" binding:"required,min=3,max=40,alphanum"`
Password string `json:"password" binding:"required,min=8,max=40"`
}
type LoginRequest struct {
Login string `json:"login" binding:"required"`
Password string `json:"password" binding:"required"`
}
type LoginResponse struct {
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) {
var account *SignupRequest
if c.BindJSON(&account) != nil {
return
}
var accountExists int64
if err := s.DB.Model(&Account{}).Where("login = ?", account.Login).Count(&accountExists).Error; err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
if accountExists > 0 {
c.AbortWithError(http.StatusConflict, ErrAccountExists)
return
}
if err := s.DB.Create(NewAccount(account.Login, account.Password)).Error; err != nil {
c.AbortWithError(http.StatusConflict, err)
return
}
c.Status(http.StatusNoContent)
}
func (s *Service) Login(c *gin.Context) {
var loginRequest *LoginRequest
if c.BindJSON(&loginRequest) != nil {
return
}
account := &Account{}
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 {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
refresh_token, err := jwt.NewWithClaims(&jwt.SigningMethodEd25519{}, NewJWTRefreshToken(account.ID)).SignedString(s.SessionKey)
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) {
auth := strings.Split(c.GetHeader("Authorization"), " ")
if len(auth) != 2 {
c.AbortWithError(http.StatusForbidden, ErrAccountTokenMissing)
return
}
if auth[0] != "Bearer" {
c.AbortWithError(http.StatusForbidden, ErrAccountTokenMissing)
return
}
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() {
ac := s.Gin.Group("/account")
ac.POST("/signup", s.Signup)
ac.POST("/login", s.Login)
ac.GET("/refresh", s.LoginRefresh)
}