-
Notifications
You must be signed in to change notification settings - Fork 9
/
oauth_handlers.go
82 lines (74 loc) · 2.32 KB
/
oauth_handlers.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 main
import (
"encoding/gob"
"fmt"
"log"
"net/http"
"net/url"
"github.com/gorilla/sessions"
"github.com/tejo/boxed/datastore"
"github.com/tejo/boxed/dropbox"
)
// handlers in this files are not actively in use, eventually will be removed
func account(w http.ResponseWriter, r *http.Request) {
withSession(w, r, func(session *sessions.Session) {
var AccessToken dropbox.AccessToken
if email := session.Values["email"]; email == nil {
fmt.Fprint(w, "no email found")
return
}
email := session.Values["email"].(string)
AccessToken, _ = datastore.LoadUserToken(email)
dbc := dropbox.NewClient(AccessToken, config.AppToken)
info, err := dbc.GetAccountInfo()
if err != nil {
// access token is not valid anymore
// reset session
session.Values["email"] = ""
session.Save(r, w)
fmt.Fprint(w, "access token not valid")
return
}
fmt.Fprintf(w, "info = %+v\n", info)
})
}
func login(w http.ResponseWriter, r *http.Request) {
withSession(w, r, func(session *sessions.Session) {
RequestToken, _ := dropbox.StartAuth(config.AppToken)
session.Values["RequestToken"] = RequestToken
url, _ := url.Parse(config.HostWithProtocol + config.CallbackURL)
authURL := dropbox.GetAuthorizeURL(RequestToken, url)
session.Save(r, w)
http.Redirect(w, r, authURL.String(), 302)
})
}
// saves the user id in session, save used data and access token in
// db, creates the default folders
func callback(w http.ResponseWriter, r *http.Request) {
withSession(w, r, func(session *sessions.Session) {
RequestToken := session.Values["RequestToken"].(dropbox.RequestToken)
AccessToken, _ := dropbox.FinishAuth(config.AppToken, RequestToken)
dbc := dropbox.NewClient(AccessToken, config.AppToken)
info, err := dbc.GetAccountInfo()
if err != nil {
log.Println(err)
}
datastore.SaveUserData(info, AccessToken)
session.Values["email"] = info.Email
session.Save(r, w)
dbc.CreateDir("drafts")
dbc.CreateDir("published")
http.Redirect(w, r, "/", 302)
})
}
func withSession(w http.ResponseWriter, r *http.Request, fn func(*sessions.Session)) {
gob.Register(dropbox.RequestToken{})
store := sessions.NewCookieStore([]byte("182hetsgeih8765$aasdhj"))
store.Options = &sessions.Options{
Path: "/",
MaxAge: 86400 * 30 * 12,
HttpOnly: true,
}
session, _ := store.Get(r, "boxedsession")
fn(session)
}