lavender/auth/providers/basic.go

64 lines
1.5 KiB
Go
Raw Permalink Normal View History

package providers
2024-10-06 21:30:39 +01:00
import (
"context"
"database/sql"
"errors"
"github.com/1f349/lavender/auth"
2025-01-19 12:04:25 +00:00
"github.com/1f349/lavender/auth/authContext"
2024-10-06 21:30:39 +01:00
"github.com/1f349/lavender/database"
"net/http"
)
type basicLoginDB interface {
auth.LookupUserDB
2024-10-06 21:30:39 +01:00
CheckLogin(ctx context.Context, un, pw string) (database.CheckLoginResult, error)
}
var _ auth.Provider = (*BasicLogin)(nil)
2024-10-06 21:30:39 +01:00
type BasicLogin struct {
DB basicLoginDB
}
2024-12-09 18:40:18 +00:00
func (b *BasicLogin) AccessState() auth.State { return auth.StateUnauthorized }
2024-10-06 21:30:39 +01:00
func (b *BasicLogin) Name() string { return "basic" }
2025-01-19 12:04:25 +00:00
func (b *BasicLogin) RenderTemplate(ctx authContext.TemplateContext) error {
2024-12-09 18:40:18 +00:00
// TODO(melon): rewrite this
2025-01-19 12:04:25 +00:00
req := ctx.Request()
un := req.FormValue("login")
redirect := req.FormValue("redirect")
if redirect == "" {
redirect = "/"
}
ctx.Render(struct {
UserEmail string
Redirect string
}{
UserEmail: un,
Redirect: redirect,
})
return nil
2024-10-06 21:30:39 +01:00
}
2025-01-19 12:04:25 +00:00
func (b *BasicLogin) AttemptLogin(ctx authContext.TemplateContext) error {
req := ctx.Request()
2024-10-06 21:30:39 +01:00
un := req.FormValue("username")
pw := req.FormValue("password")
if len(pw) < 8 {
return auth.BasicUserSafeError(http.StatusBadRequest, "Password too short")
2024-10-06 21:30:39 +01:00
}
2025-01-19 12:04:25 +00:00
login, err := b.DB.CheckLogin(ctx.Context(), un, pw)
2024-10-06 21:30:39 +01:00
switch {
case err == nil:
2025-01-19 12:04:25 +00:00
return auth.LookupUser(ctx.Context(), b.DB, login.Subject, ctx.User())
2024-10-06 21:30:39 +01:00
case errors.Is(err, sql.ErrNoRows):
return auth.BasicUserSafeError(http.StatusForbidden, "Username or password is invalid")
2024-10-06 21:30:39 +01:00
default:
return err
}
}