Compare commits

..

2 Commits

Author SHA1 Message Date
40ed60bca6 Improve SQL 2024-08-27 15:46:54 -04:00
69ecae6c26 Fix signin and signup redirect 2024-08-27 15:44:54 -04:00
3 changed files with 17 additions and 28 deletions

View File

@ -50,7 +50,7 @@ func (u Users) PostSignup(w http.ResponseWriter, r *http.Request) {
}
http.SetCookie(w, &cookie)
http.Redirect(w, r, "/users/me", http.StatusFound)
http.Redirect(w, r, "/user", http.StatusFound)
}
func (u Users) GetSignin(w http.ResponseWriter, r *http.Request) {
@ -89,7 +89,7 @@ func (u Users) PostSignin(w http.ResponseWriter, r *http.Request) {
}
http.SetCookie(w, &cookie)
fmt.Fprintf(w, "User authenticated: %+v", user)
http.Redirect(w, r, "/user", http.StatusFound)
}
func (u Users) GetSignout(w http.ResponseWriter, r *http.Request) {

View File

@ -61,27 +61,17 @@ func (ss *SessionService) Create(userID int) (*Session, error) {
Token: token,
TokenHash: hash(token),
}
row := ss.DB.QueryRow(`
UPDATE sessions
SET token_hash = $2
WHERE user_id = $1
RETURNING id;
`, session.UserID, session.TokenHash)
err = row.Scan(&session.ID)
if err == sql.ErrNoRows {
row = ss.DB.QueryRow(`
INSERT INTO sessions (user_id, token_hash)
VALUES ($1, $2)
VALUES ($1, $2) ON CONFLICT (user_id) DO
UPDATE
SET token_hash = $2
RETURNING id;
`, session.UserID, session.TokenHash)
err = row.Scan(&session.ID)
}
if err != nil {
return nil, fmt.Errorf("create: %w", err)
}
return &session, nil
}
@ -97,20 +87,19 @@ func (ss *SessionService) Delete(token string) error {
func (ss *SessionService) User(token string) (*User, error) {
token_hash := hash(token)
var user User
row := ss.DB.QueryRow(`
SELECT (user_id) FROM sessions WHERE token_hash = $1;
SELECT users.id,
users.email,
users.password_hash
FROM sessions
JOIN users ON users.id = sessions.user_id
WHERE sessions.token_hash = $1;
`, token_hash)
err := row.Scan(&user.ID)
if err != nil {
return nil, fmt.Errorf("user: %w", err)
}
row = ss.DB.QueryRow(`
SELECT email, password_hash
FROM users WHERE id = $1;
`, user.ID)
err = row.Scan(&user.Email, &user.PasswordHash)
err := row.Scan(&user.ID, &user.Email, &user.PasswordHash)
if err != nil {
return nil, fmt.Errorf("user: %w", err)
}
return &user, err
}

View File

@ -1,5 +1,5 @@
CREATE TABLE sessions (
id SERIAL PRIMARY KEY,
user_id INT UNIQUE,
user_id INT UNIQUE REFERENCES users (id) ON DELETE CASCADE,
token_hash TEXT UNIQUE NOT NULL
);