forked from unixpickle/gscrape
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.go
82 lines (71 loc) · 1.9 KB
/
auth.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
74
75
76
77
78
79
80
81
82
package gscrape
import (
"errors"
"net/http"
"net/http/cookiejar"
"net/url"
"github.com/yhat/scrape"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
// spoofedUserAgent is necessary in order to get some
// Google websites to give us a usable response.
var spoofedUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:40.0) Gecko/20100101 " +
"Firefox/40.0"
// A Session facilitates a connection to an authenticated Google service.
type Session struct {
http.Client
}
// NewSession creates a fresh, unauthenticated session.
func NewSession() *Session {
jar, _ := cookiejar.New(nil)
return &Session{http.Client{Jar: jar}}
}
// Auth attempts to access a given URL, then enters the given
// credentials when the URL redirects to a login page.
func (s *Session) Auth(serviceURL, authURL, email, password string) error {
resp, err := s.Get(serviceURL)
if err != nil {
return err
}
defer resp.Body.Close()
parsed, err := html.ParseFragment(resp.Body, nil)
if err != nil || len(parsed) == 0 {
return err
}
root := parsed[0]
form, ok := scrape.Find(root, scrape.ById("gaia_loginform"))
if !ok {
return errors.New("failed to process login page")
}
submission := url.Values{}
for _, input := range scrape.FindAll(form, scrape.ByTag(atom.Input)) {
submission.Add(getAttribute(input, "name"), getAttribute(input, "value"))
}
submission["Email"] = []string{email}
submission["Passwd"] = []string{password}
postResp, err := s.PostForm(authURL, submission)
if err != nil {
return err
}
postResp.Body.Close()
if postResp.Request.Method == "POST" {
return errors.New("login incorrect")
}
return nil
}
func (s *Session) Logout() error {
resp, err := s.Get("https://accounts.google.com/Logout")
if resp != nil {
resp.Body.Close()
}
return err
}
func getAttribute(n *html.Node, name string) string {
for _, a := range n.Attr {
if a.Key == name {
return a.Val
}
}
return ""
}