OAuth

/app/lib/auth/gothic.go (2.2 KB)

 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package auth

import (
"github.com/markbates/goth"
"github.com/pkg/errors"
"github.com/valyala/fasthttp"

"{{{ .Package }}}/app/controller/csession"
"{{{ .Package }}}/app/lib/user"
"{{{ .Package }}}/app/util"
)

const defaultProfilePath = "/profile"

func BeginAuthHandler(prv *Provider, rc *fasthttp.RequestCtx, websess util.ValueMap, logger util.Logger) (string, error) {
u, err := getAuthURL(prv, rc, websess, logger)
if err != nil {
return "", err
}
refer := string(rc.QueryArgs().Peek("refer"))
if refer != "" && refer != defaultProfilePath {
_ = csession.StoreInSession(csession.ReferKey, refer, rc, websess, logger)
}
return u, nil
}

func CompleteUserAuth(prv *Provider, rc *fasthttp.RequestCtx, websess util.ValueMap, logger util.Logger) (*user.Account, user.Accounts, error) {
value, err := csession.GetFromSession(prv.ID, websess)
if err != nil {
return nil, nil, err
}

defer func() {
_ = removeProviderData(rc, websess, logger)
}()

g, err := gothFor(rc, prv)
if err != nil {
return nil, nil, errors.Wrap(err, "unable to create oauth provider")
}

sess, err := g.UnmarshalSession(value)
if err != nil {
return nil, nil, err
}

err = validateState(rc, sess)
if err != nil {
return nil, nil, err
}

u, err := g.FetchUser(sess)
if err == nil {
return addToSession(u.Provider, u.Email, u.AvatarURL, u.AccessToken, rc, websess, logger)
}

_, err = sess.Authorize(g, &params{q: rc.QueryArgs()})
if err != nil {
return nil, nil, err
}

err = csession.StoreInSession(prv.ID, sess.Marshal(), rc, websess, logger)
if err != nil {
return nil, nil, err
}

gu, err := g.FetchUser(sess)
if err != nil {
return nil, nil, err
}

return addToSession(gu.Provider, gu.Email, gu.AvatarURL, gu.AccessToken, rc, websess, logger)
}

func gothFor(rc *fasthttp.RequestCtx, prv *Provider) (goth.Provider, error) {
proto := string(rc.URI().Scheme())
host := string(rc.URI().Host())
if host == "" {
host = "localhost"
}
return prv.Goth(proto, host)
}

func Logout(rc *fasthttp.RequestCtx, websess util.ValueMap, logger util.Logger, prvKeys ...string) error {
a := getCurrentAuths(websess)
n := a.Purge(prvKeys...)
return setCurrentAuths(n, rc, websess, logger)
}