Files
backend/handlers/auth/postLogin.go
Yi-Ting Shih 1cf3a9ef0b
All checks were successful
Go test / run-go-vet (push) Successful in 6s
Go test / check-swagger-up-to-date (push) Successful in 10s
Go test / run-go-test (push) Successful in 36s
Go test / cleanup-go-test (push) Successful in 14s
Go test / release-image (push) Successful in 3m20s
Fix: cookie timeout
2025-12-12 02:09:46 +08:00

78 lines
1.7 KiB
Go

package auth
import (
"encoding/json"
"io"
"net/http"
"time"
"gitea.konchin.com/go2025/backend/middlewares"
"gitea.konchin.com/go2025/backend/utils"
"github.com/spf13/viper"
"github.com/uptrace/bunrouter"
)
type postLoginInput struct {
Token string `json:"token"`
}
// PostLogin
//
// @param payload body postLoginInput true "payload"
// @success 200
// @router /auth/login [post]
func (self *Handlers) PostLogin(
w http.ResponseWriter, req bunrouter.Request,
) error {
ctx := req.Context()
b, err := io.ReadAll(req.Body)
if err != nil {
return middlewares.HTTPError{
StatusCode: http.StatusBadRequest,
Message: "failed to read payload",
OriginError: err,
}
}
var input postLoginInput
if err := json.Unmarshal(b, &input); err != nil {
return middlewares.HTTPError{
StatusCode: http.StatusBadRequest,
Message: "failed to unmarshal json",
OriginError: err,
}
}
session, err := self.db.GetSessionByLoginToken(ctx, input.Token)
if err != nil {
return middlewares.HTTPError{
StatusCode: http.StatusUnauthorized,
Message: "session not found",
OriginError: err,
}
}
session, err = self.db.UpdateRefreshToken(ctx, session.UserId)
if err != nil {
return middlewares.HTTPError{
StatusCode: http.StatusInternalServerError,
Message: "failed to update refresh token",
OriginError: err,
}
}
http.SetCookie(w, &http.Cookie{
Name: "refresh_token",
Value: session.RefreshToken,
Path: "/",
Secure: viper.GetBool("https"),
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
Expires: time.Now().Add(time.Duration(
viper.GetInt64("refresh-token-timeout")) * time.Second),
})
return utils.Success(w)
}