aboutsummaryrefslogtreecommitdiffstats
path: root/store.go
blob: c0ee33b8ff23d51292f626e25a7a1b1c51b3f8d1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package main

import (
	"database/sql"
	"log"

	_ "github.com/lib/pq"
)

type Session struct {
	Id     string
	UserId int64
}

type User struct {
	Id       int64
	UserName string
	Password []byte
}

type Store interface {
	GetSession(id string) (*Session, bool)
	GetUser(name string) (*User, bool)
}

type PgStore struct {
	*sql.DB
	sessionCache map[string]*Session
}

func NewPgStore() *PgStore {
	db, err := sql.Open("postgres", "postgres://auth_master:pass@localhost/authdb")
	if err != nil {
		log.Panic(err)
	}
	return &PgStore{db, make(map[string]*Session)}
}

func (store *PgStore) GetSession(id string) (*Session, bool) {
	s, ok := store.sessionCache[id]
	if ok {
		return s, true
	}
	s = new(Session)
	row := store.QueryRow("SELECT id, user_id FROM session WHERE id = $1", id)
	if err := row.Scan(s.Id, s.UserId); err != nil {
		return nil, false
	}
	return s, true
}

func (store *PgStore) GetUser(name string) (*User, bool) {
	u := new(User)
	row := store.QueryRow("SELECT id, user_name, password FROM user WHERE user_name = $1", name)
	if err := row.Scan(u.Id, u.UserName, u.Password); err != nil {
		return nil, false
	}
	return u, true
}