lavender/auth/providers/login.go

51 lines
1.3 KiB
Go
Raw Normal View History

package providers
2024-10-06 21:30:39 +01:00
import (
"context"
"database/sql"
"errors"
2024-12-09 18:40:18 +00:00
"fmt"
"github.com/1f349/lavender/auth"
2024-10-06 21:30:39 +01:00
"github.com/1f349/lavender/database"
2024-12-09 18:40:18 +00:00
"html/template"
2024-10-06 21:30:39 +01:00
"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" }
2024-12-09 18:40:18 +00:00
func (b *BasicLogin) RenderTemplate(ctx context.Context, req *http.Request, user *database.User) (template.HTML, error) {
// TODO(melon): rewrite this
return template.HTML(fmt.Sprintf("<div>%s</div>", req.FormValue("username"))), nil
2024-10-06 21:30:39 +01:00
}
func (b *BasicLogin) AttemptLogin(ctx context.Context, req *http.Request, user *database.User) error {
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
}
login, err := b.DB.CheckLogin(ctx, un, pw)
switch {
case err == nil:
2024-12-09 18:40:18 +00:00
return auth.LookupUser(ctx, b.DB, login.Subject, 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
}
}