From 1a90c059e716a90c9132fd211df9adda038b8950 Mon Sep 17 00:00:00 2001 From: Frédéric Guillot Date: Fri, 1 Dec 2017 21:51:22 -0800 Subject: Store tokens in database instead of cookie --- storage/migration.go | 2 +- storage/token.go | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 storage/token.go (limited to 'storage') diff --git a/storage/migration.go b/storage/migration.go index 994e2dd..5060a34 100644 --- a/storage/migration.go +++ b/storage/migration.go @@ -12,7 +12,7 @@ import ( "github.com/miniflux/miniflux2/sql" ) -const schemaVersion = 2 +const schemaVersion = 3 // Migrate run database migrations. func (s *Storage) Migrate() { diff --git a/storage/token.go b/storage/token.go new file mode 100644 index 0000000..dd14704 --- /dev/null +++ b/storage/token.go @@ -0,0 +1,48 @@ +// 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/miniflux2/helper" + "github.com/miniflux/miniflux2/model" +) + +// CreateToken creates a new token. +func (s *Storage) CreateToken() (*model.Token, error) { + token := model.Token{ + ID: helper.GenerateRandomString(32), + Value: helper.GenerateRandomString(64), + } + + query := "INSERT INTO tokens (id, value) VALUES ($1, $2)" + _, err := s.db.Exec(query, token.ID, token.Value) + if err != nil { + return nil, fmt.Errorf("unable to create token: %v", err) + } + + return &token, nil +} + +// Token returns a Token. +func (s *Storage) Token(id string) (*model.Token, error) { + var token model.Token + + query := "SELECT id, value FROM tokens WHERE id=$1" + err := s.db.QueryRow(query, id).Scan( + &token.ID, + &token.Value, + ) + + if err == sql.ErrNoRows { + return nil, fmt.Errorf("token not found: %s", id) + } else if err != nil { + return nil, fmt.Errorf("unable to fetch token: %v", err) + } + + return &token, nil +} -- cgit v1.2.3