Store sessions
This commit is contained in:
@@ -69,5 +69,10 @@ func Authenticate(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
http.SetCookie(w, &cookie)
|
||||
|
||||
err = models.StoreSessionToken(tokenString, loginForm.Username, expirationTime.Unix())
|
||||
if err != nil {
|
||||
log.Fatal("Failed to store session token: ", err)
|
||||
}
|
||||
|
||||
log.Printf(`| {"user": %s, "time": %d}`, loginForm.Username, time.Now().Unix())
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package models
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/golang-jwt/jwt/v4"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
@@ -25,13 +26,19 @@ type Claims struct {
|
||||
|
||||
// Private functions
|
||||
|
||||
func getUserPass(user string) (string, error) {
|
||||
func openDB() *SQLite {
|
||||
var d SQLite
|
||||
err := d.Initialize("../src/data.db")
|
||||
if err != nil {
|
||||
log.Fatal("Failed to get into DB: ", err)
|
||||
}
|
||||
|
||||
return &d
|
||||
}
|
||||
|
||||
func getUserPass(user string) (string, error) {
|
||||
d := openDB()
|
||||
|
||||
query := `
|
||||
SELECT password FROM users WHERE name='` + user + `';
|
||||
`
|
||||
@@ -58,6 +65,30 @@ func getUserPass(user string) (string, error) {
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func insertToken(token string, user string, expirationDate int64) error {
|
||||
d := openDB()
|
||||
|
||||
query := `
|
||||
INSERT INTO
|
||||
sessions(user, token, expires)
|
||||
values(
|
||||
'` + user + `',
|
||||
'` + token + `',
|
||||
` + strconv.Itoa(int(expirationDate)) + `
|
||||
);
|
||||
`
|
||||
|
||||
log.Println(query)
|
||||
|
||||
_, err := d.DB.Exec(query)
|
||||
if err != nil {
|
||||
log.Fatal("Failed to insert data: ", err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Public functions
|
||||
|
||||
func ValidateCredentials(lf *LoginForm) bool {
|
||||
@@ -70,3 +101,12 @@ func ValidateCredentials(lf *LoginForm) bool {
|
||||
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func StoreSessionToken(token string, user string, expirationDate int64) error {
|
||||
err := insertToken(token, user, expirationDate)
|
||||
if err != nil {
|
||||
log.Fatal("Unable to insert token into DB: ", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -7,6 +7,13 @@ CREATE TABLE IF NOT EXISTS users(
|
||||
password TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sessions(
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user TEXT NOT NULL UNIQUE,
|
||||
token TEXT NOT NULL,
|
||||
expires INTEGER
|
||||
);
|
||||
|
||||
-- pass is kika here
|
||||
INSERT INTO
|
||||
users(name, password)
|
||||
|
||||
Reference in New Issue
Block a user