package auth import ( "math" "net/http" "time" "git.sleepycat.moe/sam/mercury/internal/database" "github.com/flosch/pongo2/v6" "github.com/rs/zerolog/log" ) func (app *Auth) GetLogin(w http.ResponseWriter, r *http.Request) { app.Template(w, r, "auth/login.tpl", pongo2.Context{ "totp": false, }) } func (app *Auth) PostLogin(w http.ResponseWriter, r *http.Request) { ctx := r.Context() username := r.FormValue("username") password := r.FormValue("password") if username == "" { app.Flash(w, "Username cannot be empty.") app.Template(w, r, "auth/login.tpl", pongo2.Context{ "totp": false, "flash_message": "Username cannot be empty.", }) return } else if password == "" { app.Flash(w, "Password cannot be empty.") app.Template(w, r, "auth/login.tpl", pongo2.Context{ "totp": false, "flash_message": "Password cannot be empty.", }) return } conn, err := app.Database.Acquire(ctx) if err != nil { log.Err(err).Msg("acquiring database connection") return } defer conn.Release() acct, err := app.Account(conn).ByUsername(ctx, username, "") if err != nil { log.Err(err).Msg("finding account") app.Flash(w, "Username or password is invalid.") app.Template(w, r, "auth/login.tpl", pongo2.Context{ "totp": false, "flash_message": "Username or password is invalid.", }) return } passwordValid, _ := acct.PasswordValid(password) if !passwordValid { app.Template(w, r, "auth/login.tpl", pongo2.Context{ "totp": false, "flash_message": "Username or password is invalid.", }) return } // TODO: totp // create a new token token, err := app.Token(conn).Create( ctx, acct.ID, *app.DBConfig.Get().InternalApplication, database.TokenScopes{database.TokenScopeAll}, time.Now().Add(math.MaxInt64)) if err != nil { log.Err(err).Msg("creating token") return } ts, err := app.TokenToJWT(token) if err != nil { log.Err(err).Msg("signing token string") return } http.SetCookie(w, &http.Cookie{ Name: database.TokenCookieName, Value: ts, Path: "/", Expires: token.Expires, }) http.Redirect(w, r, "/web", http.StatusSeeOther) }