Compare commits
7 Commits
95294686b7
...
8b558eaf5f
| Author | SHA1 | Date | |
|---|---|---|---|
| 8b558eaf5f | |||
| e465da6854 | |||
| a582b75c82 | |||
| b3a405016e | |||
| ee6cff4104 | |||
| d8ea9f79c6 | |||
| 24cb8ecb6e |
@@ -34,6 +34,7 @@ require (
|
|||||||
github.com/go-redis/redis/v8 v8.11.5 // indirect
|
github.com/go-redis/redis/v8 v8.11.5 // indirect
|
||||||
github.com/go-viper/mapstructure/v2 v2.2.1 // indirect
|
github.com/go-viper/mapstructure/v2 v2.2.1 // indirect
|
||||||
github.com/goccy/go-json v0.10.5 // indirect
|
github.com/goccy/go-json v0.10.5 // indirect
|
||||||
|
github.com/gofrs/uuid/v5 v5.3.2 // indirect
|
||||||
github.com/google/uuid v1.6.0 // indirect
|
github.com/google/uuid v1.6.0 // indirect
|
||||||
github.com/jackc/pgerrcode v0.0.0-20240316143900-6e2875d9b438 // indirect
|
github.com/jackc/pgerrcode v0.0.0-20240316143900-6e2875d9b438 // indirect
|
||||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
|
|||||||
@@ -49,6 +49,8 @@ github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIx
|
|||||||
github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||||
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||||
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||||
|
github.com/gofrs/uuid/v5 v5.3.2 h1:2jfO8j3XgSwlz/wHqemAEugfnTlikAYHhnqQ8Xh4fE0=
|
||||||
|
github.com/gofrs/uuid/v5 v5.3.2/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8=
|
||||||
github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8=
|
github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8=
|
||||||
github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
|
github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
|
||||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||||
|
|||||||
@@ -77,7 +77,6 @@ func (a *authControllerImpl) Login(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, response)
|
c.JSON(http.StatusOK, response)
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// @Summary Request password reset email
|
// @Summary Request password reset email
|
||||||
@@ -106,7 +105,6 @@ func (a *authControllerImpl) PasswordResetBegin(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, response)
|
c.JSON(http.StatusOK, response)
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// @Summary Complete password reset via email code
|
// @Summary Complete password reset via email code
|
||||||
@@ -118,7 +116,24 @@ func (a *authControllerImpl) PasswordResetBegin(c *gin.Context) {
|
|||||||
// @Success 200 {object} models.PasswordResetCompleteResponse " "
|
// @Success 200 {object} models.PasswordResetCompleteResponse " "
|
||||||
// @Success 403 "Wrong verification code or username"
|
// @Success 403 "Wrong verification code or username"
|
||||||
func (a *authControllerImpl) PasswordResetComplete(c *gin.Context) {
|
func (a *authControllerImpl) PasswordResetComplete(c *gin.Context) {
|
||||||
c.Status(http.StatusNotImplemented)
|
|
||||||
|
request, ok := utils.GetRequest[models.PasswordResetCompleteRequest](c)
|
||||||
|
if !ok {
|
||||||
|
c.Status(http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := a.auth.PasswordResetComplete(request.Body)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, errs.ErrForbidden) {
|
||||||
|
c.Status(http.StatusForbidden)
|
||||||
|
} else {
|
||||||
|
c.Status(http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, response)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -131,7 +146,32 @@ func (a *authControllerImpl) PasswordResetComplete(c *gin.Context) {
|
|||||||
// @Success 200 {object} models.RefreshResponse " "
|
// @Success 200 {object} models.RefreshResponse " "
|
||||||
// @Failure 401 "Invalid refresh token"
|
// @Failure 401 "Invalid refresh token"
|
||||||
func (a *authControllerImpl) Refresh(c *gin.Context) {
|
func (a *authControllerImpl) Refresh(c *gin.Context) {
|
||||||
c.Status(http.StatusNotImplemented)
|
|
||||||
|
request, ok := utils.GetRequest[models.RefreshRequest](c)
|
||||||
|
if !ok {
|
||||||
|
c.Status(http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := a.auth.Refresh(request.Body)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, errs.ErrTokenExpired) {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token is expired"})
|
||||||
|
} else if errors.Is(err, errs.ErrTokenInvalid) {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token is invalid"})
|
||||||
|
} else if errors.Is(err, errs.ErrWrongTokenType) {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token type"})
|
||||||
|
} else if errors.Is(err, errs.ErrSessionNotFound) {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Could not find session in database"})
|
||||||
|
} else if errors.Is(err, errs.ErrSessionTerminated) {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Session is terminated"})
|
||||||
|
} else {
|
||||||
|
c.Status(http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, response)
|
||||||
}
|
}
|
||||||
|
|
||||||
// @Summary Register an account
|
// @Summary Register an account
|
||||||
@@ -201,7 +241,7 @@ func (a *authControllerImpl) RegisterRoutes(group *gin.RouterGroup) {
|
|||||||
group.POST("/registrationBegin", middleware.RequestMiddleware[models.RegistrationBeginRequest](enums.GuestRole), a.RegistrationBegin)
|
group.POST("/registrationBegin", middleware.RequestMiddleware[models.RegistrationBeginRequest](enums.GuestRole), a.RegistrationBegin)
|
||||||
group.POST("/registrationComplete", middleware.RequestMiddleware[models.RegistrationCompleteRequest](enums.GuestRole), a.RegistrationComplete)
|
group.POST("/registrationComplete", middleware.RequestMiddleware[models.RegistrationCompleteRequest](enums.GuestRole), a.RegistrationComplete)
|
||||||
group.POST("/login", middleware.RequestMiddleware[models.LoginRequest](enums.GuestRole), a.Login)
|
group.POST("/login", middleware.RequestMiddleware[models.LoginRequest](enums.GuestRole), a.Login)
|
||||||
group.POST("/refresh", middleware.RequestMiddleware[models.RegistrationBeginRequest](enums.UserRole), a.Refresh)
|
group.POST("/refresh", middleware.RequestMiddleware[models.RefreshRequest](enums.GuestRole), a.Refresh)
|
||||||
group.POST("/passwordResetBegin", middleware.RequestMiddleware[models.PasswordResetBeginRequest](enums.GuestRole), a.PasswordResetBegin)
|
group.POST("/passwordResetBegin", middleware.RequestMiddleware[models.PasswordResetBeginRequest](enums.GuestRole), a.PasswordResetBegin)
|
||||||
group.POST("/passwordResetComplete", middleware.RequestMiddleware[models.RegistrationBeginRequest](enums.GuestRole), a.PasswordResetComplete)
|
group.POST("/passwordResetComplete", middleware.RequestMiddleware[models.PasswordResetCompleteRequest](enums.GuestRole), a.PasswordResetComplete)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -63,15 +63,16 @@ type ProfileSetting struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type Session struct {
|
type Session struct {
|
||||||
ID int64
|
ID int64
|
||||||
UserID int64
|
UserID int64
|
||||||
Guid pgtype.UUID
|
Guid pgtype.UUID
|
||||||
Name *string
|
Name *string
|
||||||
Platform *string
|
Platform *string
|
||||||
LatestIp *string
|
LatestIp *string
|
||||||
LoginTime pgtype.Timestamp
|
LoginTime pgtype.Timestamp
|
||||||
LastSeenDate pgtype.Timestamp
|
LastRefreshExpTime pgtype.Timestamp
|
||||||
Terminated *bool
|
LastSeenDate pgtype.Timestamp
|
||||||
|
Terminated *bool
|
||||||
}
|
}
|
||||||
|
|
||||||
type User struct {
|
type User struct {
|
||||||
|
|||||||
@@ -201,7 +201,7 @@ func (q *Queries) CreateProfileSettings(ctx context.Context, profileID int64) (P
|
|||||||
|
|
||||||
const createSession = `-- name: CreateSession :one
|
const createSession = `-- name: CreateSession :one
|
||||||
INSERT INTO sessions(user_id, name, platform, latest_ip)
|
INSERT INTO sessions(user_id, name, platform, latest_ip)
|
||||||
VALUES ($1, $2, $3, $4) RETURNING id, user_id, guid, name, platform, latest_ip, login_time, last_seen_date, terminated
|
VALUES ($1, $2, $3, $4) RETURNING id, user_id, guid, name, platform, latest_ip, login_time, last_refresh_exp_time, last_seen_date, terminated
|
||||||
`
|
`
|
||||||
|
|
||||||
type CreateSessionParams struct {
|
type CreateSessionParams struct {
|
||||||
@@ -227,6 +227,7 @@ func (q *Queries) CreateSession(ctx context.Context, arg CreateSessionParams) (S
|
|||||||
&i.Platform,
|
&i.Platform,
|
||||||
&i.LatestIp,
|
&i.LatestIp,
|
||||||
&i.LoginTime,
|
&i.LoginTime,
|
||||||
|
&i.LastRefreshExpTime,
|
||||||
&i.LastSeenDate,
|
&i.LastSeenDate,
|
||||||
&i.Terminated,
|
&i.Terminated,
|
||||||
)
|
)
|
||||||
@@ -484,6 +485,56 @@ func (q *Queries) GetProfilesRestricted(ctx context.Context, arg GetProfilesRest
|
|||||||
return items, nil
|
return items, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const getSessionByGuid = `-- name: GetSessionByGuid :one
|
||||||
|
SELECT id, user_id, guid, name, platform, latest_ip, login_time, last_refresh_exp_time, last_seen_date, terminated FROM sessions
|
||||||
|
WHERE guid = ($1::text)::uuid
|
||||||
|
`
|
||||||
|
|
||||||
|
func (q *Queries) GetSessionByGuid(ctx context.Context, guid string) (Session, error) {
|
||||||
|
row := q.db.QueryRow(ctx, getSessionByGuid, guid)
|
||||||
|
var i Session
|
||||||
|
err := row.Scan(
|
||||||
|
&i.ID,
|
||||||
|
&i.UserID,
|
||||||
|
&i.Guid,
|
||||||
|
&i.Name,
|
||||||
|
&i.Platform,
|
||||||
|
&i.LatestIp,
|
||||||
|
&i.LoginTime,
|
||||||
|
&i.LastRefreshExpTime,
|
||||||
|
&i.LastSeenDate,
|
||||||
|
&i.Terminated,
|
||||||
|
)
|
||||||
|
return i, err
|
||||||
|
}
|
||||||
|
|
||||||
|
const getUnexpiredTerminatedSessionsGuids = `-- name: GetUnexpiredTerminatedSessionsGuids :many
|
||||||
|
SELECT guid FROM sessions
|
||||||
|
WHERE
|
||||||
|
terminated IS TRUE AND
|
||||||
|
last_refresh_exp_time > CURRENT_TIMESTAMP
|
||||||
|
`
|
||||||
|
|
||||||
|
func (q *Queries) GetUnexpiredTerminatedSessionsGuids(ctx context.Context) ([]pgtype.UUID, error) {
|
||||||
|
rows, err := q.db.Query(ctx, getUnexpiredTerminatedSessionsGuids)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var items []pgtype.UUID
|
||||||
|
for rows.Next() {
|
||||||
|
var guid pgtype.UUID
|
||||||
|
if err := rows.Scan(&guid); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
items = append(items, guid)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return items, nil
|
||||||
|
}
|
||||||
|
|
||||||
const getUser = `-- name: GetUser :one
|
const getUser = `-- name: GetUser :one
|
||||||
SELECT id, username, verified, registration_date, deleted FROM users
|
SELECT id, username, verified, registration_date, deleted FROM users
|
||||||
WHERE id = $1
|
WHERE id = $1
|
||||||
@@ -608,41 +659,6 @@ func (q *Queries) GetUserByUsername(ctx context.Context, username string) (User,
|
|||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
||||||
const getUserSessions = `-- name: GetUserSessions :many
|
|
||||||
SELECT id, user_id, guid, name, platform, latest_ip, login_time, last_seen_date, terminated FROM sessions
|
|
||||||
WHERE user_id = $1 AND terminated IS FALSE
|
|
||||||
`
|
|
||||||
|
|
||||||
func (q *Queries) GetUserSessions(ctx context.Context, userID int64) ([]Session, error) {
|
|
||||||
rows, err := q.db.Query(ctx, getUserSessions, userID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
var items []Session
|
|
||||||
for rows.Next() {
|
|
||||||
var i Session
|
|
||||||
if err := rows.Scan(
|
|
||||||
&i.ID,
|
|
||||||
&i.UserID,
|
|
||||||
&i.Guid,
|
|
||||||
&i.Name,
|
|
||||||
&i.Platform,
|
|
||||||
&i.LatestIp,
|
|
||||||
&i.LoginTime,
|
|
||||||
&i.LastSeenDate,
|
|
||||||
&i.Terminated,
|
|
||||||
); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
items = append(items, i)
|
|
||||||
}
|
|
||||||
if err := rows.Err(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return items, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
const getValidConfirmationCodeByCode = `-- name: GetValidConfirmationCodeByCode :one
|
const getValidConfirmationCodeByCode = `-- name: GetValidConfirmationCodeByCode :one
|
||||||
SELECT id, user_id, code_type, code_hash, expires_at, used, deleted FROM confirmation_codes
|
SELECT id, user_id, code_type, code_hash, expires_at, used, deleted FROM confirmation_codes
|
||||||
WHERE
|
WHERE
|
||||||
@@ -778,6 +794,44 @@ func (q *Queries) GetValidUserByLoginCredentials(ctx context.Context, arg GetVal
|
|||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const getValidUserSessions = `-- name: GetValidUserSessions :many
|
||||||
|
SELECT id, user_id, guid, name, platform, latest_ip, login_time, last_refresh_exp_time, last_seen_date, terminated FROM sessions
|
||||||
|
WHERE
|
||||||
|
user_id = $1 AND terminated IS FALSE AND
|
||||||
|
last_refresh_exp_time > CURRENT_TIMESTAMP
|
||||||
|
`
|
||||||
|
|
||||||
|
func (q *Queries) GetValidUserSessions(ctx context.Context, userID int64) ([]Session, error) {
|
||||||
|
rows, err := q.db.Query(ctx, getValidUserSessions, userID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var items []Session
|
||||||
|
for rows.Next() {
|
||||||
|
var i Session
|
||||||
|
if err := rows.Scan(
|
||||||
|
&i.ID,
|
||||||
|
&i.UserID,
|
||||||
|
&i.Guid,
|
||||||
|
&i.Name,
|
||||||
|
&i.Platform,
|
||||||
|
&i.LatestIp,
|
||||||
|
&i.LoginTime,
|
||||||
|
&i.LastRefreshExpTime,
|
||||||
|
&i.LastSeenDate,
|
||||||
|
&i.Terminated,
|
||||||
|
); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
items = append(items, i)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return items, nil
|
||||||
|
}
|
||||||
|
|
||||||
const pruneExpiredConfirmationCodes = `-- name: PruneExpiredConfirmationCodes :exec
|
const pruneExpiredConfirmationCodes = `-- name: PruneExpiredConfirmationCodes :exec
|
||||||
DELETE FROM confirmation_codes
|
DELETE FROM confirmation_codes
|
||||||
WHERE expires_at < CURRENT_TIMESTAMP
|
WHERE expires_at < CURRENT_TIMESTAMP
|
||||||
@@ -975,19 +1029,21 @@ SET
|
|||||||
platform = COALESCE($3, platform),
|
platform = COALESCE($3, platform),
|
||||||
latest_ip = COALESCE($4, latest_ip),
|
latest_ip = COALESCE($4, latest_ip),
|
||||||
login_time = COALESCE($5, login_time),
|
login_time = COALESCE($5, login_time),
|
||||||
last_seen_date = COALESCE($6, last_seen_date),
|
last_refresh_exp_time = COALESCE($6, last_refresh_exp_time),
|
||||||
terminated = COALESCE($7, terminated)
|
last_seen_date = COALESCE($7, last_seen_date),
|
||||||
|
terminated = COALESCE($8, terminated)
|
||||||
WHERE id = $1
|
WHERE id = $1
|
||||||
`
|
`
|
||||||
|
|
||||||
type UpdateSessionParams struct {
|
type UpdateSessionParams struct {
|
||||||
ID int64
|
ID int64
|
||||||
Name *string
|
Name *string
|
||||||
Platform *string
|
Platform *string
|
||||||
LatestIp *string
|
LatestIp *string
|
||||||
LoginTime pgtype.Timestamp
|
LoginTime pgtype.Timestamp
|
||||||
LastSeenDate pgtype.Timestamp
|
LastRefreshExpTime pgtype.Timestamp
|
||||||
Terminated *bool
|
LastSeenDate pgtype.Timestamp
|
||||||
|
Terminated *bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (q *Queries) UpdateSession(ctx context.Context, arg UpdateSessionParams) error {
|
func (q *Queries) UpdateSession(ctx context.Context, arg UpdateSessionParams) error {
|
||||||
@@ -997,6 +1053,7 @@ func (q *Queries) UpdateSession(ctx context.Context, arg UpdateSessionParams) er
|
|||||||
arg.Platform,
|
arg.Platform,
|
||||||
arg.LatestIp,
|
arg.LatestIp,
|
||||||
arg.LoginTime,
|
arg.LoginTime,
|
||||||
|
arg.LastRefreshExpTime,
|
||||||
arg.LastSeenDate,
|
arg.LastSeenDate,
|
||||||
arg.Terminated,
|
arg.Terminated,
|
||||||
)
|
)
|
||||||
|
|||||||
32
backend/internal/dto/claims.go
Normal file
32
backend/internal/dto/claims.go
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
// Copyright (c) 2025 Nikolai Papin
|
||||||
|
//
|
||||||
|
// This file is part of Easywish
|
||||||
|
//
|
||||||
|
// This program is free software: you can redistribute it and/or modify
|
||||||
|
// it under the terms of the GNU General Public License as published by
|
||||||
|
// the Free Software Foundation, either version 3 of the License, or
|
||||||
|
// (at your option) any later version.
|
||||||
|
//
|
||||||
|
// This program is distributed in the hope that it will be useful,
|
||||||
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
|
||||||
|
// the GNU General Public License for more details.
|
||||||
|
//
|
||||||
|
// You should have received a copy of the GNU General Public License
|
||||||
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
package dto
|
||||||
|
|
||||||
|
import (
|
||||||
|
"easywish/internal/utils/enums"
|
||||||
|
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
type UserClaims struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
Role enums.Role `json:"role"`
|
||||||
|
Type enums.JwtTokenType `json:"type"`
|
||||||
|
Session string `json:"session"`
|
||||||
|
jwt.RegisteredClaims
|
||||||
|
}
|
||||||
23
backend/internal/dto/request.go
Normal file
23
backend/internal/dto/request.go
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
// Copyright (c) 2025 Nikolai Papin
|
||||||
|
//
|
||||||
|
// This file is part of Easywish
|
||||||
|
//
|
||||||
|
// This program is free software: you can redistribute it and/or modify
|
||||||
|
// it under the terms of the GNU General Public License as published by
|
||||||
|
// the Free Software Foundation, either version 3 of the License, or
|
||||||
|
// (at your option) any later version.
|
||||||
|
//
|
||||||
|
// This program is distributed in the hope that it will be useful,
|
||||||
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
|
||||||
|
// the GNU General Public License for more details.
|
||||||
|
//
|
||||||
|
// You should have received a copy of the GNU General Public License
|
||||||
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
package dto
|
||||||
|
|
||||||
|
type Request[T any] struct {
|
||||||
|
User ClientInfo
|
||||||
|
Body T
|
||||||
|
}
|
||||||
27
backend/internal/dto/sessionInfo.go
Normal file
27
backend/internal/dto/sessionInfo.go
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
|
||||||
|
// Copyright (c) 2025 Nikolai Papin
|
||||||
|
//
|
||||||
|
// This file is part of Easywish
|
||||||
|
//
|
||||||
|
// This program is free software: you can redistribute it and/or modify
|
||||||
|
// it under the terms of the GNU General Public License as published by
|
||||||
|
// the Free Software Foundation, either version 3 of the License, or
|
||||||
|
// (at your option) any later version.
|
||||||
|
//
|
||||||
|
// This program is distributed in the hope that it will be useful,
|
||||||
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
|
||||||
|
// the GNU General Public License for more details.
|
||||||
|
//
|
||||||
|
// You should have received a copy of the GNU General Public License
|
||||||
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
package dto
|
||||||
|
|
||||||
|
import "easywish/internal/utils/enums"
|
||||||
|
|
||||||
|
type SessionInfo struct {
|
||||||
|
Username string
|
||||||
|
Session string
|
||||||
|
Role enums.Role
|
||||||
|
}
|
||||||
24
backend/internal/dto/userInfo.go
Normal file
24
backend/internal/dto/userInfo.go
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
// Copyright (c) 2025 Nikolai Papin
|
||||||
|
//
|
||||||
|
// This file is part of Easywish
|
||||||
|
//
|
||||||
|
// This program is free software: you can redistribute it and/or modify
|
||||||
|
// it under the terms of the GNU General Public License as published by
|
||||||
|
// the Free Software Foundation, either version 3 of the License, or
|
||||||
|
// (at your option) any later version.
|
||||||
|
//
|
||||||
|
// This program is distributed in the hope that it will be useful,
|
||||||
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
|
||||||
|
// the GNU General Public License for more details.
|
||||||
|
//
|
||||||
|
// You should have received a copy of the GNU General Public License
|
||||||
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
package dto
|
||||||
|
|
||||||
|
type ClientInfo struct {
|
||||||
|
SessionInfo
|
||||||
|
IP string
|
||||||
|
UserAgent string
|
||||||
|
}
|
||||||
@@ -29,4 +29,10 @@ var (
|
|||||||
ErrInvalidCredentials = errors.New("Invalid username, password or TOTP code")
|
ErrInvalidCredentials = errors.New("Invalid username, password or TOTP code")
|
||||||
ErrInvalidToken = errors.New("Token is invalid or expired")
|
ErrInvalidToken = errors.New("Token is invalid or expired")
|
||||||
ErrServerError = errors.New("Internal server error")
|
ErrServerError = errors.New("Internal server error")
|
||||||
|
|
||||||
|
ErrTokenExpired = errors.New("Token is expired")
|
||||||
|
ErrTokenInvalid = errors.New("Token is invalid")
|
||||||
|
ErrWrongTokenType = errors.New("Invalid token type")
|
||||||
|
ErrSessionNotFound = errors.New("Could not find session in database")
|
||||||
|
ErrSessionTerminated = errors.New("Session is terminated")
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -18,64 +18,53 @@
|
|||||||
package middleware
|
package middleware
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"easywish/config"
|
"easywish/internal/dto"
|
||||||
|
"easywish/internal/services"
|
||||||
"easywish/internal/utils/enums"
|
"easywish/internal/utils/enums"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/golang-jwt/jwt/v5"
|
"go.uber.org/zap"
|
||||||
|
errs "easywish/internal/errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Claims struct {
|
func AuthMiddleware(log *zap.Logger, auth services.AuthService) gin.HandlerFunc {
|
||||||
Username string `json:"username"`
|
|
||||||
Role enums.Role `json:"role"`
|
|
||||||
jwt.RegisteredClaims
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: validate token type
|
|
||||||
// TODO: validate session guid
|
|
||||||
func AuthMiddleware() gin.HandlerFunc {
|
|
||||||
return func(c *gin.Context) {
|
return func(c *gin.Context) {
|
||||||
cfg := config.GetConfig()
|
|
||||||
authHeader := c.GetHeader("Authorization")
|
authHeader := c.GetHeader("Authorization")
|
||||||
|
|
||||||
if authHeader == "" {
|
if authHeader == "" {
|
||||||
c.Set("username", nil)
|
|
||||||
c.Set("role", enums.GuestRole)
|
c.Set("session_info", dto.SessionInfo{
|
||||||
|
Username: "",
|
||||||
|
Session: "",
|
||||||
|
Role: enums.GuestRole},
|
||||||
|
)
|
||||||
c.Next()
|
c.Next()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
tokenString := authHeader
|
tokenString := authHeader
|
||||||
|
if sessionInfo, err := auth.ValidateToken(tokenString, enums.JwtAccessTokenType); err != nil {
|
||||||
token, err := jwt.ParseWithClaims(
|
if errors.Is(err, errs.ErrTokenExpired) {
|
||||||
tokenString,
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Token is expired"})
|
||||||
&Claims{},
|
} else if errors.Is(err, errs.ErrTokenInvalid) {
|
||||||
func(token *jwt.Token) (any, error) {
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Token is invalid"})
|
||||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
} else if errors.Is(err, errs.ErrWrongTokenType) {
|
||||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token type"})
|
||||||
}
|
} else if errors.Is(err, errs.ErrSessionNotFound) {
|
||||||
return []byte(cfg.JwtSecret), nil
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Could not find session in database"})
|
||||||
},
|
} else if errors.Is(err, errs.ErrSessionTerminated) {
|
||||||
)
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Session is terminated"})
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
if errors.Is(err, jwt.ErrTokenExpired) {
|
|
||||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Token expired"})
|
|
||||||
} else {
|
} else {
|
||||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
|
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "Internal server error"})
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
|
} else {
|
||||||
|
c.Set("session_info", sessionInfo)
|
||||||
|
c.Next()
|
||||||
}
|
}
|
||||||
|
|
||||||
if claims, ok := token.Claims.(*Claims); ok && token.Valid {
|
return
|
||||||
c.Set("username", claims.Username)
|
|
||||||
c.Set("role", claims.Role)
|
|
||||||
c.Next()
|
|
||||||
} else {
|
|
||||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid claims"})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,6 +18,7 @@
|
|||||||
package middleware
|
package middleware
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"easywish/internal/dto"
|
||||||
"easywish/internal/utils/enums"
|
"easywish/internal/utils/enums"
|
||||||
"easywish/internal/validation"
|
"easywish/internal/validation"
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -27,58 +28,51 @@ import (
|
|||||||
"github.com/go-playground/validator/v10"
|
"github.com/go-playground/validator/v10"
|
||||||
)
|
)
|
||||||
|
|
||||||
type UserInfo struct {
|
|
||||||
Username string
|
|
||||||
Role enums.Role
|
|
||||||
}
|
|
||||||
|
|
||||||
type Request[T any] struct {
|
|
||||||
User UserInfo
|
|
||||||
Body T
|
|
||||||
}
|
|
||||||
|
|
||||||
const requestKey = "request"
|
const requestKey = "request"
|
||||||
|
|
||||||
func UserInfoFromContext(c *gin.Context) (*UserInfo, bool) {
|
func ClientInfoFromContext(c *gin.Context) (*dto.ClientInfo, bool) {
|
||||||
|
|
||||||
var username any
|
|
||||||
var role any
|
|
||||||
var ok bool
|
var ok bool
|
||||||
|
|
||||||
username, ok = c.Get("username") ; if !ok {
|
ip := c.ClientIP()
|
||||||
return &UserInfo{Username: "", Role: enums.GuestRole}, true
|
userAgent := c.Request.UserAgent()
|
||||||
}
|
|
||||||
|
|
||||||
role, ok = c.Get("role"); if !ok {
|
sessionInfoFromCtx, ok := c.Get("session_info"); if !ok {
|
||||||
return nil, false
|
return nil, false
|
||||||
}
|
}
|
||||||
|
|
||||||
if username == nil {
|
sessionInfo := sessionInfoFromCtx.(dto.SessionInfo)
|
||||||
return &UserInfo{Username: "", Role: enums.GuestRole}, true
|
|
||||||
|
if sessionInfo.Username == "" {
|
||||||
|
return &dto.ClientInfo{
|
||||||
|
SessionInfo: sessionInfo,
|
||||||
|
IP: ip,
|
||||||
|
UserAgent: userAgent,
|
||||||
|
}, true
|
||||||
}
|
}
|
||||||
|
|
||||||
if role == nil {
|
return &dto.ClientInfo{
|
||||||
return nil, false
|
SessionInfo: sessionInfo,
|
||||||
}
|
IP: ip,
|
||||||
|
UserAgent: userAgent,
|
||||||
return &UserInfo{Username: username.(string), Role: role.(enums.Role)}, true
|
}, true
|
||||||
}
|
}
|
||||||
|
|
||||||
func RequestFromContext[T any](c *gin.Context) Request[T] {
|
func RequestFromContext[T any](c *gin.Context) dto.Request[T] {
|
||||||
return c.Value(requestKey).(Request[T])
|
return c.Value(requestKey).(dto.Request[T])
|
||||||
}
|
}
|
||||||
|
|
||||||
func RequestMiddleware[T any](role enums.Role) gin.HandlerFunc {
|
func RequestMiddleware[T any](role enums.Role) gin.HandlerFunc {
|
||||||
return gin.HandlerFunc(func(c *gin.Context) {
|
return gin.HandlerFunc(func(c *gin.Context) {
|
||||||
|
|
||||||
userInfo, ok := UserInfoFromContext(c)
|
clientInfo, ok := ClientInfoFromContext(c)
|
||||||
|
|
||||||
if !ok {
|
if !ok {
|
||||||
c.Status(http.StatusUnauthorized)
|
c.Status(http.StatusUnauthorized)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if userInfo.Role < role {
|
if clientInfo.Role < role {
|
||||||
c.Status(http.StatusForbidden)
|
c.Status(http.StatusForbidden)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -99,8 +93,8 @@ func RequestMiddleware[T any](role enums.Role) gin.HandlerFunc {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
request := Request[T]{
|
request := dto.Request[T]{
|
||||||
User: *userInfo,
|
User: *clientInfo,
|
||||||
Body: body,
|
Body: body,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -20,13 +20,15 @@ package routes
|
|||||||
import (
|
import (
|
||||||
"easywish/internal/controllers"
|
"easywish/internal/controllers"
|
||||||
"easywish/internal/middleware"
|
"easywish/internal/middleware"
|
||||||
|
"easywish/internal/services"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
|
"go.uber.org/zap"
|
||||||
)
|
)
|
||||||
|
|
||||||
func NewRouter(engine *gin.Engine, groups []RouteGroup) *gin.Engine {
|
func NewRouter(engine *gin.Engine, log *zap.Logger, auth services.AuthService, groups []RouteGroup) *gin.Engine {
|
||||||
apiGroup := engine.Group("/api")
|
apiGroup := engine.Group("/api")
|
||||||
apiGroup.Use(middleware.AuthMiddleware())
|
apiGroup.Use(middleware.AuthMiddleware(log, auth))
|
||||||
for _, group := range groups {
|
for _, group := range groups {
|
||||||
subgroup := apiGroup.Group(group.BasePath)
|
subgroup := apiGroup.Group(group.BasePath)
|
||||||
subgroup.Use(group.Middleware...)
|
subgroup.Use(group.Middleware...)
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"easywish/config"
|
"easywish/config"
|
||||||
"easywish/internal/database"
|
"easywish/internal/database"
|
||||||
|
"easywish/internal/dto"
|
||||||
errs "easywish/internal/errors"
|
errs "easywish/internal/errors"
|
||||||
"easywish/internal/models"
|
"easywish/internal/models"
|
||||||
"easywish/internal/utils"
|
"easywish/internal/utils"
|
||||||
@@ -30,6 +31,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/go-redis/redis/v8"
|
"github.com/go-redis/redis/v8"
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"github.com/jackc/pgerrcode"
|
"github.com/jackc/pgerrcode"
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
@@ -43,6 +45,7 @@ type AuthService interface {
|
|||||||
Refresh(request models.RefreshRequest) (*models.RefreshResponse, error)
|
Refresh(request models.RefreshRequest) (*models.RefreshResponse, error)
|
||||||
PasswordResetBegin(request models.PasswordResetBeginRequest) (bool, error)
|
PasswordResetBegin(request models.PasswordResetBeginRequest) (bool, error)
|
||||||
PasswordResetComplete(request models.PasswordResetCompleteRequest) (*models.PasswordResetCompleteResponse, error)
|
PasswordResetComplete(request models.PasswordResetCompleteRequest) (*models.PasswordResetCompleteResponse, error)
|
||||||
|
ValidateToken(token string, tokenType enums.JwtTokenType) (*dto.SessionInfo, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type authServiceImpl struct {
|
type authServiceImpl struct {
|
||||||
@@ -53,7 +56,27 @@ type authServiceImpl struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewAuthService(_log *zap.Logger, _dbctx database.DbContext, _redis *redis.Client, _smtp SmtpService) AuthService {
|
func NewAuthService(_log *zap.Logger, _dbctx database.DbContext, _redis *redis.Client, _smtp SmtpService) AuthService {
|
||||||
return &authServiceImpl{log: _log, dbctx: _dbctx, redis: _redis, smtp: _smtp}
|
|
||||||
|
authService := &authServiceImpl{log: _log, dbctx: _dbctx, redis: _redis, smtp: _smtp}
|
||||||
|
|
||||||
|
// Cache terminated sessions
|
||||||
|
// FIXME: review possible RAM overflow
|
||||||
|
db := database.NewDbHelper(_dbctx)
|
||||||
|
guids, err := db.Queries.GetUnexpiredTerminatedSessionsGuids(db.CTX)
|
||||||
|
if err != nil {
|
||||||
|
panic("Failed to load terminated sessions' GUIDs")
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := context.TODO()
|
||||||
|
// FIXME: review possible problems due to a large pipeline request
|
||||||
|
pipe := _redis.Pipeline()
|
||||||
|
for _, guid := range guids {
|
||||||
|
if err := pipe.Set(ctx, fmt.Sprintf("session::%s::is_terminated", guid), true, 0).Err(); err != nil {
|
||||||
|
panic("Failed to cache terminated session: " + err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_log.Info("Cached terminated sessions' GUIDs in Redis", zap.Int("amount", len(guids)))
|
||||||
|
return authService
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *authServiceImpl) RegistrationBegin(request models.RegistrationBeginRequest) (bool, error) {
|
func (a *authServiceImpl) RegistrationBegin(request models.RegistrationBeginRequest) (bool, error) {
|
||||||
@@ -75,7 +98,25 @@ func (a *authServiceImpl) RegistrationBegin(request models.RegistrationBeginRequ
|
|||||||
|
|
||||||
defer helper.RollbackOnError(err)
|
defer helper.RollbackOnError(err)
|
||||||
|
|
||||||
// TODO: check occupation with redis
|
if isInProgress, err := a.redis.Get(
|
||||||
|
context.TODO(),
|
||||||
|
fmt.Sprintf("email::%s::registration_in_progress",
|
||||||
|
request.Email),
|
||||||
|
).Bool(); err != nil {
|
||||||
|
if err != redis.Nil {
|
||||||
|
a.log.Error(
|
||||||
|
"Failed to look up cached registration_in_progress state of email as part of registration procedure",
|
||||||
|
zap.String("email", request.Email),
|
||||||
|
zap.Error(err))
|
||||||
|
return false, errs.ErrServerError
|
||||||
|
}
|
||||||
|
isInProgress = false
|
||||||
|
} else if isInProgress {
|
||||||
|
a.log.Warn(
|
||||||
|
"Attempted to begin registration on email that is in progress of registration or on cooldown",
|
||||||
|
zap.String("email", request.Email))
|
||||||
|
return false, errs.ErrTooManyRequests
|
||||||
|
}
|
||||||
|
|
||||||
if occupationStatus, err = db.TXQueries.CheckUserRegistrationAvailability(db.CTX, database.CheckUserRegistrationAvailabilityParams{
|
if occupationStatus, err = db.TXQueries.CheckUserRegistrationAvailability(db.CTX, database.CheckUserRegistrationAvailabilityParams{
|
||||||
Email: request.Email,
|
Email: request.Email,
|
||||||
@@ -98,7 +139,19 @@ func (a *authServiceImpl) RegistrationBegin(request models.RegistrationBeginRequ
|
|||||||
|
|
||||||
} else if occupationStatus.EmailBusy {
|
} else if occupationStatus.EmailBusy {
|
||||||
// Falsely confirm in order to avoid disclosing registered email addresses
|
// Falsely confirm in order to avoid disclosing registered email addresses
|
||||||
// TODO: save this email into redis
|
if err := a.redis.Set(
|
||||||
|
context.TODO(),
|
||||||
|
fmt.Sprintf("email::%s::registration_in_progress", request.Email),
|
||||||
|
true,
|
||||||
|
time.Duration(10 * time.Minute), // XXX: magic number
|
||||||
|
).Err(); err != nil {
|
||||||
|
a.log.Error(
|
||||||
|
"Failed to falsely set cache registration_in_progress state for email as a measure to prevent email enumeration",
|
||||||
|
zap.String("email", request.Email),
|
||||||
|
zap.Error(err))
|
||||||
|
return false, errs.ErrServerError
|
||||||
|
}
|
||||||
|
|
||||||
a.log.Warn(
|
a.log.Warn(
|
||||||
"Attempted registration for a taken email",
|
"Attempted registration for a taken email",
|
||||||
zap.String("email", request.Email),
|
zap.String("email", request.Email),
|
||||||
@@ -191,6 +244,19 @@ func (a *authServiceImpl) RegistrationBegin(request models.RegistrationBeginRequ
|
|||||||
zap.String("code", generatedCode))
|
zap.String("code", generatedCode))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := a.redis.Set(
|
||||||
|
context.TODO(),
|
||||||
|
fmt.Sprintf("email::%s::registration_in_progress", request.Email),
|
||||||
|
true,
|
||||||
|
time.Duration(10 * time.Minute), // XXX: magic number
|
||||||
|
).Err(); err != nil {
|
||||||
|
a.log.Error(
|
||||||
|
"Failed to cache registration_in_progress state for email",
|
||||||
|
zap.String("email", request.Email),
|
||||||
|
zap.Error(err))
|
||||||
|
return false, errs.ErrServerError
|
||||||
|
}
|
||||||
|
|
||||||
if err = helper.Commit(); err != nil {
|
if err = helper.Commit(); err != nil {
|
||||||
a.log.Error(
|
a.log.Error(
|
||||||
"Failed to commit transaction",
|
"Failed to commit transaction",
|
||||||
@@ -324,7 +390,8 @@ func (a *authServiceImpl) RegistrationComplete(request models.RegistrationComple
|
|||||||
return nil, errs.ErrServerError
|
return nil, errs.ErrServerError
|
||||||
}
|
}
|
||||||
|
|
||||||
accessToken, refreshToken, err = utils.GenerateTokens(user.Username, session.Guid.String())
|
// TODO: get user role
|
||||||
|
accessToken, refreshToken, err = utils.GenerateTokens(user.Username, session.Guid.String(), enums.UserRole)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.log.Error(
|
a.log.Error(
|
||||||
@@ -415,7 +482,8 @@ func (a *authServiceImpl) Login(request models.LoginRequest) (*models.LoginRespo
|
|||||||
return nil, errs.ErrServerError
|
return nil, errs.ErrServerError
|
||||||
}
|
}
|
||||||
|
|
||||||
accessToken, refreshToken, err := utils.GenerateTokens(userRow.Username, session.Guid.String())
|
// TODO: get user role
|
||||||
|
accessToken, refreshToken, err := utils.GenerateTokens(userRow.Username, session.Guid.String(), enums.UserRole)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.log.Error(
|
a.log.Error(
|
||||||
"Failed to generate tokens for a new login",
|
"Failed to generate tokens for a new login",
|
||||||
@@ -440,7 +508,136 @@ func (a *authServiceImpl) Login(request models.LoginRequest) (*models.LoginRespo
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (a *authServiceImpl) Refresh(request models.RefreshRequest) (*models.RefreshResponse, error) {
|
func (a *authServiceImpl) Refresh(request models.RefreshRequest) (*models.RefreshResponse, error) {
|
||||||
return nil, errs.ErrNotImplemented
|
|
||||||
|
sessionInfo, err := a.ValidateToken(request.RefreshToken, enums.JwtRefreshTokenType); if err != nil {
|
||||||
|
|
||||||
|
if utils.ErrorIsOneOf(
|
||||||
|
err,
|
||||||
|
errs.ErrInvalidToken,
|
||||||
|
errs.ErrTokenExpired,
|
||||||
|
errs.ErrWrongTokenType,
|
||||||
|
errs.ErrSessionNotFound,
|
||||||
|
errs.ErrSessionTerminated,
|
||||||
|
) {
|
||||||
|
return nil, err
|
||||||
|
} else {
|
||||||
|
a.log.Error(
|
||||||
|
"Encountered an unexpected error while validating token",
|
||||||
|
zap.Error(err))
|
||||||
|
return nil, errs.ErrServerError
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
accessToken, refreshToken, err := utils.GenerateTokens(
|
||||||
|
sessionInfo.Username,
|
||||||
|
sessionInfo.Session,
|
||||||
|
sessionInfo.Role,
|
||||||
|
); if err != nil {
|
||||||
|
a.log.Error(
|
||||||
|
"Failed to generate tokens for user during refresh",
|
||||||
|
zap.String("username", sessionInfo.Username),
|
||||||
|
zap.String("session", sessionInfo.Session),
|
||||||
|
zap.Error(err))
|
||||||
|
return nil, errs.ErrServerError
|
||||||
|
}
|
||||||
|
|
||||||
|
response := models.RefreshResponse{
|
||||||
|
Tokens: models.Tokens{
|
||||||
|
AccessToken: accessToken,
|
||||||
|
RefreshToken: refreshToken,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
return &response, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *authServiceImpl) ValidateToken(jwtToken string, tokenType enums.JwtTokenType) (*dto.SessionInfo, error) {
|
||||||
|
|
||||||
|
var err error
|
||||||
|
|
||||||
|
token, err := jwt.ParseWithClaims(
|
||||||
|
jwtToken,
|
||||||
|
&dto.UserClaims{},
|
||||||
|
func(token *jwt.Token) (any, error) {
|
||||||
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||||
|
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||||
|
}
|
||||||
|
return []byte(config.GetConfig().JwtSecret), nil
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, jwt.ErrTokenExpired) {
|
||||||
|
return nil, errs.ErrTokenExpired
|
||||||
|
}
|
||||||
|
return nil, errs.ErrInvalidToken
|
||||||
|
}
|
||||||
|
|
||||||
|
claims, ok := token.Claims.(*dto.UserClaims); if ok && token.Valid {
|
||||||
|
|
||||||
|
if claims.Type != tokenType {
|
||||||
|
return nil, errs.ErrWrongTokenType
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := context.TODO()
|
||||||
|
isTerminated, redisErr := a.redis.Get(ctx, fmt.Sprintf("session::%s::is_terminated", claims.Session)).Bool()
|
||||||
|
if redisErr != nil && redisErr != redis.Nil {
|
||||||
|
a.log.Error(
|
||||||
|
"Failed to lookup cache to check whether session is not terminated",
|
||||||
|
zap.Error(redisErr))
|
||||||
|
return nil, redisErr
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cache if nil
|
||||||
|
if redisErr == redis.Nil {
|
||||||
|
db := database.NewDbHelper(a.dbctx)
|
||||||
|
|
||||||
|
session, err := db.Queries.GetSessionByGuid(db.CTX, claims.Session)
|
||||||
|
if err != nil {
|
||||||
|
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
a.log.Warn(
|
||||||
|
"Session does not exist or was deleted",
|
||||||
|
zap.String("session", claims.Session))
|
||||||
|
return nil, errs.ErrSessionNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
a.log.Error(
|
||||||
|
"Failed to lookup session in database",
|
||||||
|
zap.String("session", claims.Session),
|
||||||
|
zap.Error(err))
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := a.redis.Set(
|
||||||
|
ctx,
|
||||||
|
fmt.Sprintf("session::%s::is_terminated", claims.Session),
|
||||||
|
*session.Terminated,
|
||||||
|
time.Duration(8 * time.Hour), // XXX: magic number
|
||||||
|
).Err(); err != nil {
|
||||||
|
a.log.Error(
|
||||||
|
"Failed to cache session's is_terminated state",
|
||||||
|
zap.String("session", claims.Session),
|
||||||
|
zap.Error(err))
|
||||||
|
// c.AbortWithStatus(http.StatusInternalServerError)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
isTerminated = *session.Terminated
|
||||||
|
}
|
||||||
|
|
||||||
|
if isTerminated {
|
||||||
|
return nil, errs.ErrSessionTerminated
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sessionInfo := dto.SessionInfo{
|
||||||
|
Username: claims.Username,
|
||||||
|
Session: claims.Session,
|
||||||
|
Role: claims.Role,
|
||||||
|
}
|
||||||
|
|
||||||
|
return &sessionInfo, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *authServiceImpl) PasswordResetBegin(request models.PasswordResetBeginRequest) (bool, error) {
|
func (a *authServiceImpl) PasswordResetBegin(request models.PasswordResetBeginRequest) (bool, error) {
|
||||||
@@ -654,7 +851,8 @@ func (a *authServiceImpl) PasswordResetComplete(request models.PasswordResetComp
|
|||||||
zap.Error(err))
|
zap.Error(err))
|
||||||
}
|
}
|
||||||
|
|
||||||
if accessToken, refreshToken, err = utils.GenerateTokens(user.Username, session.Guid.String()); err != nil {
|
// TODO: get user role
|
||||||
|
if accessToken, refreshToken, err = utils.GenerateTokens(user.Username, session.Guid.String(), enums.UserRole); err != nil {
|
||||||
a.log.Error(
|
a.log.Error(
|
||||||
"Failed to generate tokens as part of user password reset",
|
"Failed to generate tokens as part of user password reset",
|
||||||
zap.String("email", request.Email),
|
zap.String("email", request.Email),
|
||||||
|
|||||||
29
backend/internal/utils/errors.go
Normal file
29
backend/internal/utils/errors.go
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
// Copyright (c) 2025 Nikolai Papin
|
||||||
|
//
|
||||||
|
// This file is part of Easywish
|
||||||
|
//
|
||||||
|
// This program is free software: you can redistribute it and/or modify
|
||||||
|
// it under the terms of the GNU General Public License as published by
|
||||||
|
// the Free Software Foundation, either version 3 of the License, or
|
||||||
|
// (at your option) any later version.
|
||||||
|
//
|
||||||
|
// This program is distributed in the hope that it will be useful,
|
||||||
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
|
||||||
|
// the GNU General Public License for more details.
|
||||||
|
//
|
||||||
|
// You should have received a copy of the GNU General Public License
|
||||||
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
package utils
|
||||||
|
|
||||||
|
import "errors"
|
||||||
|
|
||||||
|
func ErrorIsOneOf(err error, ignoreErrors ...error) bool {
|
||||||
|
for _, ignore := range ignoreErrors {
|
||||||
|
if errors.Is(err, ignore) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
@@ -25,22 +25,24 @@ import (
|
|||||||
"github.com/golang-jwt/jwt/v5"
|
"github.com/golang-jwt/jwt/v5"
|
||||||
)
|
)
|
||||||
|
|
||||||
func GenerateTokens(username string, sessionGuid string) (accessToken, refreshToken string, err error) {
|
func GenerateTokens(username string, sessionGuid string, role enums.Role) (accessToken, refreshToken string, err error) {
|
||||||
cfg := config.GetConfig()
|
cfg := config.GetConfig()
|
||||||
|
|
||||||
accessClaims := jwt.MapClaims{
|
accessClaims := jwt.MapClaims{
|
||||||
"username": username,
|
"username": username,
|
||||||
"guid": sessionGuid,
|
"role": role,
|
||||||
|
"session": sessionGuid,
|
||||||
"type": enums.JwtAccessTokenType,
|
"type": enums.JwtAccessTokenType,
|
||||||
"exp": time.Now().Add(time.Minute * time.Duration(cfg.JwtExpAccess)).Unix(),
|
"exp": time.Now().Add(time.Minute * time.Duration(cfg.JwtExpAccess)).Unix(),
|
||||||
}
|
}
|
||||||
accessToken, err = jwt.NewWithClaims(jwt.SigningMethodHS256, accessClaims).SignedString([]byte(cfg.JwtSecret))
|
accessToken, err = jwt.NewWithClaims(jwt.SigningMethodHS256, accessClaims).SignedString([]byte(cfg.JwtSecret))
|
||||||
|
|
||||||
refreshClaims := jwt.MapClaims{
|
refreshClaims := jwt.MapClaims{
|
||||||
"username": username,
|
"username": username,
|
||||||
"guid": sessionGuid,
|
"role": role,
|
||||||
|
"session": sessionGuid,
|
||||||
"type": enums.JwtRefreshTokenType,
|
"type": enums.JwtRefreshTokenType,
|
||||||
"exp": time.Now().Add(time.Hour * time.Duration(cfg.JwtExpRefresh)).Unix(),
|
"exp": time.Now().Add(time.Hour * time.Duration(cfg.JwtExpRefresh)).Unix(),
|
||||||
}
|
}
|
||||||
refreshToken, err = jwt.NewWithClaims(jwt.SigningMethodHS256, refreshClaims).SignedString([]byte(cfg.JwtSecret))
|
refreshToken, err = jwt.NewWithClaims(jwt.SigningMethodHS256, refreshClaims).SignedString([]byte(cfg.JwtSecret))
|
||||||
|
|
||||||
|
|||||||
@@ -1,32 +1,31 @@
|
|||||||
// Copyright (c) 2025 Nikolai Papin
|
// Copyright (c) 2025 Nikolai Papin
|
||||||
//
|
//
|
||||||
// This file is part of Easywish
|
// This file is part of Easywish
|
||||||
//
|
//
|
||||||
// This program is free software: you can redistribute it and/or modify
|
// This program is free software: you can redistribute it and/or modify
|
||||||
// it under the terms of the GNU General Public License as published by
|
// it under the terms of the GNU General Public License as published by
|
||||||
// the Free Software Foundation, either version 3 of the License, or
|
// the Free Software Foundation, either version 3 of the License, or
|
||||||
// (at your option) any later version.
|
// (at your option) any later version.
|
||||||
//
|
//
|
||||||
// This program is distributed in the hope that it will be useful,
|
// This program is distributed in the hope that it will be useful,
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
|
||||||
// the GNU General Public License for more details.
|
// the GNU General Public License for more details.
|
||||||
//
|
//
|
||||||
// You should have received a copy of the GNU General Public License
|
// You should have received a copy of the GNU General Public License
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
package utils
|
package utils
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"easywish/internal/middleware"
|
"easywish/internal/dto"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
func GetRequest[T any](c *gin.Context) (*middleware.Request[T], bool) {
|
func GetRequest[T any](c *gin.Context) (*dto.Request[T], bool) {
|
||||||
|
|
||||||
req, ok := c.Get("request")
|
req, ok := c.Get("request")
|
||||||
request := req.(middleware.Request[T])
|
request := req.(dto.Request[T])
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, false
|
return nil, false
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -238,13 +238,26 @@ SET
|
|||||||
platform = COALESCE($3, platform),
|
platform = COALESCE($3, platform),
|
||||||
latest_ip = COALESCE($4, latest_ip),
|
latest_ip = COALESCE($4, latest_ip),
|
||||||
login_time = COALESCE($5, login_time),
|
login_time = COALESCE($5, login_time),
|
||||||
last_seen_date = COALESCE($6, last_seen_date),
|
last_refresh_exp_time = COALESCE($6, last_refresh_exp_time),
|
||||||
terminated = COALESCE($7, terminated)
|
last_seen_date = COALESCE($7, last_seen_date),
|
||||||
|
terminated = COALESCE($8, terminated)
|
||||||
WHERE id = $1;
|
WHERE id = $1;
|
||||||
|
|
||||||
;-- name: GetUserSessions :many
|
;-- name: GetSessionByGuid :one
|
||||||
SELECT * FROM sessions
|
SELECT * FROM sessions
|
||||||
WHERE user_id = $1 AND terminated IS FALSE;
|
WHERE guid = (@guid::text)::uuid;
|
||||||
|
|
||||||
|
;-- name: GetValidUserSessions :many
|
||||||
|
SELECT * FROM sessions
|
||||||
|
WHERE
|
||||||
|
user_id = $1 AND terminated IS FALSE AND
|
||||||
|
last_refresh_exp_time > CURRENT_TIMESTAMP;
|
||||||
|
|
||||||
|
;-- name: GetUnexpiredTerminatedSessionsGuids :many
|
||||||
|
SELECT guid FROM sessions
|
||||||
|
WHERE
|
||||||
|
terminated IS TRUE AND
|
||||||
|
last_refresh_exp_time > CURRENT_TIMESTAMP;
|
||||||
|
|
||||||
;-- name: TerminateAllSessionsForUserByUsername :exec
|
;-- name: TerminateAllSessionsForUserByUsername :exec
|
||||||
UPDATE sessions
|
UPDATE sessions
|
||||||
|
|||||||
@@ -66,6 +66,7 @@ CREATE TABLE IF NOT EXISTS "sessions" (
|
|||||||
platform VARCHAR(32),
|
platform VARCHAR(32),
|
||||||
latest_ip VARCHAR(16),
|
latest_ip VARCHAR(16),
|
||||||
login_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
login_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
last_refresh_exp_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP + INTERVAL '10080 seconds',
|
||||||
last_seen_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
last_seen_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
terminated BOOLEAN DEFAULT FALSE
|
terminated BOOLEAN DEFAULT FALSE
|
||||||
);
|
);
|
||||||
|
|||||||
Reference in New Issue
Block a user