Feat: works on my machine
This commit is contained in:
60
middlewares/auth.go
Normal file
60
middlewares/auth.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package middlewares
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"gitea.konchin.com/ytshih/inp2025/models"
|
||||
"gitea.konchin.com/ytshih/inp2025/types"
|
||||
"github.com/uptrace/bunrouter"
|
||||
)
|
||||
|
||||
func (self *Handlers) Auth(
|
||||
next bunrouter.HandlerFunc,
|
||||
) bunrouter.HandlerFunc {
|
||||
return func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||
ctx := req.Context()
|
||||
|
||||
username, password, ok := req.BasicAuth()
|
||||
if !ok {
|
||||
return HTTPError{
|
||||
StatusCode: http.StatusNotFound,
|
||||
Message: "username not exist",
|
||||
}
|
||||
}
|
||||
|
||||
dbUser := models.User{Username: username}
|
||||
err := self.db.NewSelect().
|
||||
Model(&dbUser).
|
||||
WherePK().
|
||||
Scan(ctx)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return HTTPError{
|
||||
StatusCode: http.StatusUnauthorized,
|
||||
Message: "username not exist",
|
||||
OriginError: err,
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return HTTPError{
|
||||
StatusCode: http.StatusInternalServerError,
|
||||
Message: "failed to select user from db",
|
||||
OriginError: err,
|
||||
}
|
||||
}
|
||||
if password != dbUser.Password {
|
||||
return HTTPError{
|
||||
StatusCode: http.StatusUnauthorized,
|
||||
Message: "password incorrect",
|
||||
OriginError: err,
|
||||
}
|
||||
}
|
||||
return next(w, req.WithContext(context.WithValue(
|
||||
ctx, types.UserKey, models.User{
|
||||
Username: username,
|
||||
Password: password,
|
||||
})))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user