session validation/invalidation
This commit is contained in:
parent
1c0e541c89
commit
562ed2e015
4 changed files with 19 additions and 6 deletions
|
@ -8,6 +8,7 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"arimelody-web/log"
|
||||
"arimelody-web/model"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
@ -15,7 +16,7 @@ import (
|
|||
|
||||
const TOKEN_LEN = 64
|
||||
|
||||
func GetSessionFromRequest(db *sqlx.DB, r *http.Request) (*model.Session, error) {
|
||||
func GetSessionFromRequest(app *model.AppState, r *http.Request) (*model.Session, error) {
|
||||
sessionCookie, err := r.Cookie(model.COOKIE_TOKEN)
|
||||
if err != nil && err != http.ErrNoCookie {
|
||||
return nil, errors.New(fmt.Sprintf("Failed to retrieve session cookie: %v", err))
|
||||
|
@ -25,14 +26,26 @@ func GetSessionFromRequest(db *sqlx.DB, r *http.Request) (*model.Session, error)
|
|||
|
||||
if sessionCookie != nil {
|
||||
// fetch existing session
|
||||
session, err = GetSession(db, sessionCookie.Value)
|
||||
session, err = GetSession(app.DB, sessionCookie.Value)
|
||||
|
||||
if err != nil && !strings.Contains(err.Error(), "no rows") {
|
||||
return nil, errors.New(fmt.Sprintf("Failed to retrieve session: %v", err))
|
||||
}
|
||||
|
||||
if session != nil {
|
||||
// TODO: consider running security checks here (i.e. user agent mismatches)
|
||||
if session.UserAgent != r.UserAgent() {
|
||||
msg := "Session user agent mismatch. A cookie may have been hijacked!"
|
||||
if session.Account != nil {
|
||||
account, _ := GetAccountByID(app.DB, session.Account.ID)
|
||||
msg += " (Account \"" + account.Username + "\")"
|
||||
}
|
||||
app.Log.Warn(log.TYPE_ACCOUNT, msg)
|
||||
err = DeleteSession(app.DB, session.Token)
|
||||
if err != nil {
|
||||
app.Log.Warn(log.TYPE_ACCOUNT, "Failed to delete affected session")
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue