summaryrefslogtreecommitdiff
path: root/database/users.go
diff options
context:
space:
mode:
Diffstat (limited to 'database/users.go')
-rw-r--r--database/users.go63
1 files changed, 63 insertions, 0 deletions
diff --git a/database/users.go b/database/users.go
index d2b4f20..f9e4436 100644
--- a/database/users.go
+++ b/database/users.go
@@ -12,6 +12,12 @@ const (
ExpiryDuration = time.Hour * 24
)
+type UserApiKey struct {
+ Key string `json:"key"`
+ UserID string `json:"user_id"`
+ CreatedAt time.Time `json:"created_at"`
+}
+
type User struct {
ID string `json:"sub"`
Mail string `json:"email"`
@@ -119,3 +125,60 @@ func DeleteExpiredSessions(dbConn *sql.DB) error {
}
return nil
}
+
+func ListUserAPIKeys(dbConn *sql.DB, userId string) ([]*UserApiKey, error) {
+ rows, err := dbConn.Query(`SELECT key, user_id, created_at FROM api_keys WHERE user_id = ?;`, userId)
+ if err != nil {
+ log.Println(err)
+ return nil, err
+ }
+ defer rows.Close()
+
+ var apiKeys []*UserApiKey
+ for rows.Next() {
+ var apiKey UserApiKey
+ err := rows.Scan(&apiKey.Key, &apiKey.UserID, &apiKey.CreatedAt)
+ if err != nil {
+ log.Println(err)
+ return nil, err
+ }
+
+ apiKeys = append(apiKeys, &apiKey)
+ }
+
+ return apiKeys, nil
+}
+
+func SaveAPIKey(dbConn *sql.DB, apiKey *UserApiKey) (*UserApiKey, error) {
+ _, err := dbConn.Exec(`INSERT OR REPLACE INTO api_keys (key, user_id) VALUES (?, ?);`, apiKey.Key, apiKey.UserID)
+ if err != nil {
+ log.Println(err)
+ return nil, err
+ }
+
+ apiKey.CreatedAt = time.Now()
+ return apiKey, nil
+}
+
+func GetAPIKey(dbConn *sql.DB, key string) (*UserApiKey, error) {
+ row := dbConn.QueryRow(`SELECT key, user_id, created_at FROM api_keys WHERE key = ?;`, key)
+
+ var apiKey UserApiKey
+ err := row.Scan(&apiKey.Key, &apiKey.UserID, &apiKey.CreatedAt)
+ if err != nil {
+ log.Println(err)
+ return nil, err
+ }
+
+ return &apiKey, nil
+}
+
+func DeleteAPIKey(dbConn *sql.DB, key string) error {
+ _, err := dbConn.Exec(`DELETE FROM api_keys WHERE key = ?;`, key)
+ if err != nil {
+ log.Println(err)
+ return err
+ }
+
+ return nil
+}