forked from umputun/remark42
/
user.go
57 lines (47 loc) · 1.2 KB
/
user.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
package rest
import (
"net/http"
"github.com/go-pkgz/auth/token"
"github.com/pkg/errors"
"github.com/umputun/remark/backend/app/store"
)
// MustGetUserInfo fails if can't extract user data from the request.
// should be called from authed controllers only
func MustGetUserInfo(r *http.Request) store.User {
user, err := GetUserInfo(r)
if err != nil {
panic(err)
}
return user
}
// GetUserInfo returns user from request context
func GetUserInfo(r *http.Request) (user store.User, err error) {
u, err := token.GetUserInfo(r)
if err != nil {
return store.User{}, errors.Wrap(err, "can't extract user info from the token")
}
return store.User{
Name: u.Name,
ID: u.ID,
IP: u.IP,
Picture: u.Picture,
Admin: u.IsAdmin(),
Verified: u.BoolAttr("verified"),
Blocked: u.BoolAttr("blocked"),
}, nil
}
// SetUserInfo sets user into request context
func SetUserInfo(r *http.Request, user store.User) *http.Request {
u := token.User{
ID: user.ID,
Name: user.Name,
Picture: user.Picture,
IP: user.IP,
Attributes: map[string]interface{}{
"blocked": user.Blocked,
"verified": user.Verified,
},
}
u.SetAdmin(user.Admin)
return token.SetUserInfo(r, u)
}