From 58acd1d5e3a997d27f60549b51bdf41df900c6c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Guillot?= Date: Sat, 16 Dec 2017 12:15:33 -0800 Subject: [PATCH] Rename sessions table to user_sessions --- model/{session.go => user_session.go} | 12 +-- server/middleware/session.go | 4 +- server/ui/controller/login.go | 4 +- server/ui/controller/oauth2.go | 2 +- server/ui/controller/session.go | 4 +- sql/schema_version_9.sql | 1 + sql/sql.go | 4 +- storage/migration.go | 2 +- storage/session.go | 132 ------------------------- storage/user_session.go | 135 ++++++++++++++++++++++++++ 10 files changed, 153 insertions(+), 147 deletions(-) rename model/{session.go => user_session.go} (52%) create mode 100644 sql/schema_version_9.sql delete mode 100644 storage/session.go create mode 100644 storage/user_session.go diff --git a/model/session.go b/model/user_session.go similarity index 52% rename from model/session.go rename to model/user_session.go index 96e445d2..7112159c 100644 --- a/model/session.go +++ b/model/user_session.go @@ -7,8 +7,8 @@ package model import "time" import "fmt" -// Session represents a user session in the system. -type Session struct { +// UserSession represents a user session in the system. +type UserSession struct { ID int64 UserID int64 Token string @@ -17,9 +17,9 @@ type Session struct { IP string } -func (s *Session) String() string { - return fmt.Sprintf("ID=%d, UserID=%d, IP=%s", s.ID, s.UserID, s.IP) +func (s *UserSession) String() string { + return fmt.Sprintf(`ID="%d", UserID="%d", IP="%s", Token="%s"`, s.ID, s.UserID, s.IP, s.Token) } -// Sessions represents a list of sessions. -type Sessions []*Session +// UserSessions represents a list of sessions. +type UserSessions []*UserSession diff --git a/server/middleware/session.go b/server/middleware/session.go index a5a0b67b..3759565f 100644 --- a/server/middleware/session.go +++ b/server/middleware/session.go @@ -55,13 +55,13 @@ func (s *SessionMiddleware) isPublicRoute(r *http.Request) bool { } } -func (s *SessionMiddleware) getSessionFromCookie(r *http.Request) *model.Session { +func (s *SessionMiddleware) getSessionFromCookie(r *http.Request) *model.UserSession { sessionCookie, err := r.Cookie("sessionID") if err == http.ErrNoCookie { return nil } - session, err := s.store.SessionByToken(sessionCookie.Value) + session, err := s.store.UserSessionByToken(sessionCookie.Value) if err != nil { logger.Error("[SessionMiddleware] %v", err) return nil diff --git a/server/ui/controller/login.go b/server/ui/controller/login.go index 95704034..d130f4c8 100644 --- a/server/ui/controller/login.go +++ b/server/ui/controller/login.go @@ -47,7 +47,7 @@ func (c *Controller) CheckLogin(ctx *core.Context, request *core.Request, respon return } - sessionToken, err := c.store.CreateSession( + sessionToken, err := c.store.CreateUserSession( authForm.Username, request.Request().UserAgent(), realip.RealIP(request.Request()), @@ -77,7 +77,7 @@ func (c *Controller) Logout(ctx *core.Context, request *core.Request, response * user := ctx.LoggedUser() sessionCookie := request.Cookie("sessionID") - if err := c.store.RemoveSessionByToken(user.ID, sessionCookie); err != nil { + if err := c.store.RemoveUserSessionByToken(user.ID, sessionCookie); err != nil { logger.Error("[Controller:Logout] %v", err) } diff --git a/server/ui/controller/oauth2.go b/server/ui/controller/oauth2.go index 5c5d268f..56ed53c5 100644 --- a/server/ui/controller/oauth2.go +++ b/server/ui/controller/oauth2.go @@ -105,7 +105,7 @@ func (c *Controller) OAuth2Callback(ctx *core.Context, request *core.Request, re } } - sessionToken, err := c.store.CreateSession( + sessionToken, err := c.store.CreateUserSession( user.Username, request.Request().UserAgent(), realip.RealIP(request.Request()), diff --git a/server/ui/controller/session.go b/server/ui/controller/session.go index bc5d5e9b..a020b165 100644 --- a/server/ui/controller/session.go +++ b/server/ui/controller/session.go @@ -18,7 +18,7 @@ func (c *Controller) ShowSessions(ctx *core.Context, request *core.Request, resp return } - sessions, err := c.store.Sessions(user.ID) + sessions, err := c.store.UserSessions(user.ID) if err != nil { response.HTML().ServerError(err) return @@ -42,7 +42,7 @@ func (c *Controller) RemoveSession(ctx *core.Context, request *core.Request, res return } - err = c.store.RemoveSessionByID(user.ID, sessionID) + err = c.store.RemoveUserSessionByID(user.ID, sessionID) if err != nil { logger.Error("[Controller:RemoveSession] %v", err) } diff --git a/sql/schema_version_9.sql b/sql/schema_version_9.sql new file mode 100644 index 00000000..77617243 --- /dev/null +++ b/sql/schema_version_9.sql @@ -0,0 +1 @@ +alter table sessions rename to user_sessions; \ No newline at end of file diff --git a/sql/sql.go b/sql/sql.go index 60bbd65e..a7974e21 100644 --- a/sql/sql.go +++ b/sql/sql.go @@ -1,5 +1,5 @@ // Code generated by go generate; DO NOT EDIT. -// 2017-12-15 18:49:24.029844239 -0800 PST m=+0.002440111 +// 2017-12-16 12:08:03.005451004 -0800 PST m=+0.002264796 package sql @@ -143,6 +143,7 @@ alter table users add column entry_direction entry_sorting_direction default 'as `, "schema_version_8": `alter table feeds add column crawler boolean default 'f'; `, + "schema_version_9": `alter table sessions rename to user_sessions;`, } var SqlMapChecksums = map[string]string{ @@ -154,4 +155,5 @@ var SqlMapChecksums = map[string]string{ "schema_version_6": "9d05b4fb223f0e60efc716add5048b0ca9c37511cf2041721e20505d6d798ce4", "schema_version_7": "33f298c9aa30d6de3ca28e1270df51c2884d7596f1283a75716e2aeb634cd05c", "schema_version_8": "9922073fc4032d8922617ec6a6a07ae8d4817846c138760fb96cb5608ab83bfc", + "schema_version_9": "de5ba954752fe808a993feef5bf0c6f808e0a4ced5379de8bec8342678150892", } diff --git a/storage/migration.go b/storage/migration.go index 04ffce3b..368c567c 100644 --- a/storage/migration.go +++ b/storage/migration.go @@ -12,7 +12,7 @@ import ( "github.com/miniflux/miniflux/sql" ) -const schemaVersion = 8 +const schemaVersion = 9 // Migrate run database migrations. func (s *Storage) Migrate() { diff --git a/storage/session.go b/storage/session.go deleted file mode 100644 index dbf2dc38..00000000 --- a/storage/session.go +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2017 Frédéric Guillot. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -package storage - -import ( - "database/sql" - "fmt" - - "github.com/miniflux/miniflux/helper" - "github.com/miniflux/miniflux/model" -) - -// Sessions returns the list of sessions for the given user. -func (s *Storage) Sessions(userID int64) (model.Sessions, error) { - query := `SELECT id, user_id, token, created_at, user_agent, ip FROM sessions WHERE user_id=$1 ORDER BY id DESC` - rows, err := s.db.Query(query, userID) - if err != nil { - return nil, fmt.Errorf("unable to fetch sessions: %v", err) - } - defer rows.Close() - - var sessions model.Sessions - for rows.Next() { - var session model.Session - err := rows.Scan( - &session.ID, - &session.UserID, - &session.Token, - &session.CreatedAt, - &session.UserAgent, - &session.IP, - ) - - if err != nil { - return nil, fmt.Errorf("unable to fetch session row: %v", err) - } - - sessions = append(sessions, &session) - } - - return sessions, nil -} - -// CreateSession creates a new sessions. -func (s *Storage) CreateSession(username, userAgent, ip string) (sessionID string, err error) { - var userID int64 - - err = s.db.QueryRow("SELECT id FROM users WHERE username = $1", username).Scan(&userID) - if err != nil { - return "", fmt.Errorf("unable to fetch UserID: %v", err) - } - - token := helper.GenerateRandomString(64) - query := "INSERT INTO sessions (token, user_id, user_agent, ip) VALUES ($1, $2, $3, $4)" - _, err = s.db.Exec(query, token, userID, userAgent, ip) - if err != nil { - return "", fmt.Errorf("unable to create session: %v", err) - } - - s.SetLastLogin(userID) - - return token, nil -} - -// SessionByToken finds a session by the token. -func (s *Storage) SessionByToken(token string) (*model.Session, error) { - var session model.Session - - query := "SELECT id, user_id, token, created_at, user_agent, ip FROM sessions WHERE token = $1" - err := s.db.QueryRow(query, token).Scan( - &session.ID, - &session.UserID, - &session.Token, - &session.CreatedAt, - &session.UserAgent, - &session.IP, - ) - - if err == sql.ErrNoRows { - return nil, fmt.Errorf("session not found: %s", token) - } else if err != nil { - return nil, fmt.Errorf("unable to fetch session: %v", err) - } - - return &session, nil -} - -// RemoveSessionByToken remove a session by using the token. -func (s *Storage) RemoveSessionByToken(userID int64, token string) error { - result, err := s.db.Exec(`DELETE FROM sessions WHERE user_id=$1 AND token=$2`, userID, token) - if err != nil { - return fmt.Errorf("unable to remove this session: %v", err) - } - - count, err := result.RowsAffected() - if err != nil { - return fmt.Errorf("unable to remove this session: %v", err) - } - - if count != 1 { - return fmt.Errorf("nothing has been removed") - } - - return nil -} - -// RemoveSessionByID remove a session by using the ID. -func (s *Storage) RemoveSessionByID(userID, sessionID int64) error { - result, err := s.db.Exec(`DELETE FROM sessions WHERE user_id=$1 AND id=$2`, userID, sessionID) - if err != nil { - return fmt.Errorf("unable to remove this session: %v", err) - } - - count, err := result.RowsAffected() - if err != nil { - return fmt.Errorf("unable to remove this session: %v", err) - } - - if count != 1 { - return fmt.Errorf("nothing has been removed") - } - - return nil -} - -// FlushAllSessions removes all sessions from the database. -func (s *Storage) FlushAllSessions() (err error) { - _, err = s.db.Exec(`DELETE FROM sessions`) - return -} diff --git a/storage/user_session.go b/storage/user_session.go new file mode 100644 index 00000000..da9cebad --- /dev/null +++ b/storage/user_session.go @@ -0,0 +1,135 @@ +// Copyright 2017 Frédéric Guillot. All rights reserved. +// Use of this source code is governed by the Apache 2.0 +// license that can be found in the LICENSE file. + +package storage + +import ( + "database/sql" + "fmt" + + "github.com/miniflux/miniflux/helper" + "github.com/miniflux/miniflux/model" +) + +// UserSessions returns the list of sessions for the given user. +func (s *Storage) UserSessions(userID int64) (model.UserSessions, error) { + query := `SELECT + id, user_id, token, created_at, user_agent, ip + FROM user_sessions + WHERE user_id=$1 ORDER BY id DESC` + rows, err := s.db.Query(query, userID) + if err != nil { + return nil, fmt.Errorf("unable to fetch user sessions: %v", err) + } + defer rows.Close() + + var sessions model.UserSessions + for rows.Next() { + var session model.UserSession + err := rows.Scan( + &session.ID, + &session.UserID, + &session.Token, + &session.CreatedAt, + &session.UserAgent, + &session.IP, + ) + + if err != nil { + return nil, fmt.Errorf("unable to fetch user session row: %v", err) + } + + sessions = append(sessions, &session) + } + + return sessions, nil +} + +// CreateUserSession creates a new sessions. +func (s *Storage) CreateUserSession(username, userAgent, ip string) (sessionID string, err error) { + var userID int64 + + err = s.db.QueryRow("SELECT id FROM users WHERE username = $1", username).Scan(&userID) + if err != nil { + return "", fmt.Errorf("unable to fetch UserID: %v", err) + } + + token := helper.GenerateRandomString(64) + query := "INSERT INTO user_sessions (token, user_id, user_agent, ip) VALUES ($1, $2, $3, $4)" + _, err = s.db.Exec(query, token, userID, userAgent, ip) + if err != nil { + return "", fmt.Errorf("unable to create user session: %v", err) + } + + s.SetLastLogin(userID) + + return token, nil +} + +// UserSessionByToken finds a session by the token. +func (s *Storage) UserSessionByToken(token string) (*model.UserSession, error) { + var session model.UserSession + + query := "SELECT id, user_id, token, created_at, user_agent, ip FROM user_sessions WHERE token = $1" + err := s.db.QueryRow(query, token).Scan( + &session.ID, + &session.UserID, + &session.Token, + &session.CreatedAt, + &session.UserAgent, + &session.IP, + ) + + if err == sql.ErrNoRows { + return nil, fmt.Errorf("user session not found: %s", token) + } else if err != nil { + return nil, fmt.Errorf("unable to fetch user session: %v", err) + } + + return &session, nil +} + +// RemoveUserSessionByToken remove a session by using the token. +func (s *Storage) RemoveUserSessionByToken(userID int64, token string) error { + result, err := s.db.Exec(`DELETE FROM user_sessions WHERE user_id=$1 AND token=$2`, userID, token) + if err != nil { + return fmt.Errorf("unable to remove this user session: %v", err) + } + + count, err := result.RowsAffected() + if err != nil { + return fmt.Errorf("unable to remove this user session: %v", err) + } + + if count != 1 { + return fmt.Errorf("nothing has been removed") + } + + return nil +} + +// RemoveUserSessionByID remove a session by using the ID. +func (s *Storage) RemoveUserSessionByID(userID, sessionID int64) error { + result, err := s.db.Exec(`DELETE FROM user_sessions WHERE user_id=$1 AND id=$2`, userID, sessionID) + if err != nil { + return fmt.Errorf("unable to remove this user session: %v", err) + } + + count, err := result.RowsAffected() + if err != nil { + return fmt.Errorf("unable to remove this user session: %v", err) + } + + if count != 1 { + return fmt.Errorf("nothing has been removed") + } + + return nil +} + +// FlushAllSessions removes all user sessions from the database. +func (s *Storage) FlushAllSessions() (err error) { + _, err = s.db.Exec(`DELETE FROM user_sessions`) + return +}