Feat: add login
This commit is contained in:
73
handlers/auth/postLogin.go
Normal file
73
handlers/auth/postLogin.go
Normal file
@@ -0,0 +1,73 @@
|
||||
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 302 {object} string "redirect to root page"
|
||||
// @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.GetSession(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,
|
||||
Expires: time.Now().Add(time.Duration(
|
||||
viper.GetInt64("REFRESH_TOKEN_TIMEOUT")) * time.Second),
|
||||
})
|
||||
|
||||
return utils.Success(w)
|
||||
}
|
||||
Reference in New Issue
Block a user