/
oauth.go
98 lines (76 loc) · 2.2 KB
/
oauth.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package amelia
import (
"net/http"
"appengine"
"appengine/datastore"
"appengine/user"
)
func authorize(w http.ResponseWriter, r *http.Request) *appError {
c := appengine.NewContext(r)
u := user.Current(c)
if u == nil {
http.Redirect(w, r, "/", http.StatusUnauthorized)
return nil
}
url := oauthCfg.AuthCodeURL(u.ID)
http.Redirect(w, r, url, http.StatusSeeOther)
return nil
}
func oauthCallback(w http.ResponseWriter, r *http.Request) *appError {
c := appengine.NewContext(r)
httpErr := r.FormValue("error")
code := r.FormValue("code")
userId := r.FormValue("state")
if httpErr == "access_denied" {
http.Redirect(w, r, "/", http.StatusSeeOther)
return nil
}
t := CreateTransport(c, nil)
user := User{}
userKey := datastore.NewKey(c, "User", userId, 0, nil)
err := datastore.Get(c, userKey, &user)
if err != nil {
return &appError{err, "User not found", http.StatusNotFound}
}
token, err := t.Exchange(code)
if err != nil {
return &appError{err, "Error authorizing with Moves",
http.StatusInternalServerError}
}
user.MovesToken = *NewMonkeyToken(token)
user.AuthorizedWithMoves = true
profile, err := GetUserProfile(t)
if err != nil {
return &appError{err, "Error getting user profile from Moves",
http.StatusInternalServerError}
}
user.MovesUserId = profile.UserId
_, err = datastore.Put(c, userKey, &user)
if err != nil {
return &appError{err, "Error saving user", http.StatusInternalServerError}
}
http.Redirect(w, r, "/", http.StatusSeeOther)
return nil
}
func revoke(w http.ResponseWriter, r *http.Request) *appError {
c := appengine.NewContext(r)
u := user.Current(c)
if u == nil {
http.Redirect(w, r, "/", http.StatusUnauthorized)
return nil
}
var user User
userKey := datastore.NewKey(c, "User", u.ID, 0, nil)
err := datastore.Get(c, userKey, &user)
if err != nil {
return &appError{err, "User not found", http.StatusNotFound}
}
user.AuthorizedWithMoves = false
// TODO: See if it's possible to actually revoke access and refresh tokens
_, err = datastore.Put(c, userKey, &user)
if err != nil {
return &appError{err, "Error revoking Moves access", http.StatusInternalServerError}
}
http.Redirect(w, r, "/", http.StatusSeeOther)
return nil
}