Compare commits

..

No commits in common. "40ed60bca6a34885b945974587706e97ee84ea78" and "0fa9037164d7d418e087dace9d9471248ad67aac" have entirely different histories.

3 changed files with 28 additions and 17 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, "/user", http.StatusFound)
http.Redirect(w, r, "/users/me", 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)
http.Redirect(w, r, "/user", http.StatusFound)
fmt.Fprintf(w, "User authenticated: %+v", user)
}
func (u Users) GetSignout(w http.ResponseWriter, r *http.Request) {

View File

@ -61,17 +61,27 @@ func (ss *SessionService) Create(userID int) (*Session, error) {
Token: token,
TokenHash: hash(token),
}
row := ss.DB.QueryRow(`
INSERT INTO sessions (user_id, token_hash)
VALUES ($1, $2) ON CONFLICT (user_id) DO
UPDATE
SET token_hash = $2
RETURNING id;
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)
RETURNING id;
`, session.UserID, session.TokenHash)
err = row.Scan(&session.ID)
}
if err != nil {
return nil, fmt.Errorf("create: %w", err)
}
return &session, nil
}
@ -87,19 +97,20 @@ 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 users.id,
users.email,
users.password_hash
FROM sessions
JOIN users ON users.id = sessions.user_id
WHERE sessions.token_hash = $1;
SELECT (user_id) FROM sessions WHERE token_hash = $1;
`, token_hash)
err := row.Scan(&user.ID, &user.Email, &user.PasswordHash)
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)
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 REFERENCES users (id) ON DELETE CASCADE,
user_id INT UNIQUE,
token_hash TEXT UNIQUE NOT NULL
);