-
Notifications
You must be signed in to change notification settings - Fork 0
/
token.go
73 lines (60 loc) · 1.71 KB
/
token.go
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main
import (
"context"
"net/http"
"time"
"github.com/jackc/pgtype"
)
// Token is an access token. Required by clients to send messages.
type Token struct {
Hash string
User string
Email string
Expires time.Time
}
func (srv *Shoutyface) tokencheck(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("token")
if token == "" || srv.GetTokenUser(token) == "" {
http.Error(w, "", http.StatusForbidden)
return
}
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func (srv *Shoutyface) admintokencheck(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("token")
if token == "" || srv.GetTokenUser(token) != "admin" {
http.Error(w, "", http.StatusForbidden)
return
}
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
// GetTokenUser or return an empty string if the token doesn't exist.
func (srv *Shoutyface) GetTokenUser(t string) string {
row := srv.dbp.QueryRow(context.Background(), "select name from users inner join tokens on tokens.uid=users.id where tokens.hash=$1;", t)
var name string
err := row.Scan(&name)
if err != nil {
return ""
}
return name
}
// AddToken for a user.
func (srv *Shoutyface) AddToken(token, user string) error {
now := pgtype.Timestamp{
Time: time.Now().UTC(),
Status: pgtype.Present,
}
sql := "insert into tokens(hash,uid,expires) select $1,u.id,$3 from users u where u.name=$2;"
_, err := srv.dbp.Exec(context.Background(), sql, token, user, now)
return err
}
// DeleteToken from database.
func (srv *Shoutyface) DeleteToken(token string) {
srv.dbp.Exec(context.Background(), "delete from tokens where hash=$1;", token)
}