learnsteam-quiz-api/internal/repositories/token.go

76 lines
1.9 KiB
Go
Raw Normal View History

2023-10-19 22:47:12 +09:00
package repositories
import (
2023-11-17 01:38:01 +09:00
config "learnsteam/learsteam-quiz-api/configs"
"learnsteam/learsteam-quiz-api/internal/models"
2023-10-19 22:47:12 +09:00
"github.com/golang-jwt/jwt/v5"
"gorm.io/gorm"
)
type tokenRepository struct {
DB *gorm.DB
}
func NewTokenRepository(db *gorm.DB) TokenRepository {
return &tokenRepository{
DB: db,
}
}
type TokenRepository interface {
Generate(string, int64) (string, error)
Find(string) (*models.Token, error)
2023-11-17 01:38:01 +09:00
FindByRefreshToken(string, string) (*models.Token, error)
2023-10-19 22:47:12 +09:00
Create(*models.Token) (*models.Token, error)
Update(*models.Token) (*models.Token, error)
Delete(string) error
}
func (s *tokenRepository) Generate(sub string, expire_at int64) (string, error) {
claims := jwt.MapClaims{}
claims["authorized"] = true
claims["sub"] = sub
claims["exp"] = expire_at
at := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
token, err := at.SignedString([]byte(config.SECRET_KEY))
return token, err
}
func (r *tokenRepository) Find(id string) (*models.Token, error) {
var token *models.Token
err := r.DB.Where("id = ?", id).First(&token).Error
return token, err
}
2023-11-17 01:38:01 +09:00
func (r *tokenRepository) FindByRefreshToken(user_id string, refreshToken string) (*models.Token, error) {
var token *models.Token
err := r.DB.Where("user_id = ? AND refresh_token = ?", user_id, refreshToken).First(&token).Error
return token, err
}
2023-10-19 22:47:12 +09:00
func (r *tokenRepository) Create(token *models.Token) (*models.Token, error) {
err := r.DB.Create(&token).Error
return token, err
}
func (r *tokenRepository) Update(token *models.Token) (*models.Token, error) {
var row *models.Token
if err := r.DB.Where("id=?", token.ID).First(&row).Error; err != nil {
return nil, err
}
err := r.DB.Model(&row).Select("*").Updates(&token).Error
return row, err
}
func (r *tokenRepository) Delete(id string) error {
var token *models.Token
if err := r.DB.Where("id=?", id).First(&token).Error; err != nil {
return err
}
err := r.DB.Delete(&token).Error
return err
}