/
hub.go
324 lines (266 loc) · 7.71 KB
/
hub.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
package main
import (
"code.google.com/p/goauth2/oauth"
"github.com/google/go-github/github"
"github.com/gorilla/mux"
"github.com/gorilla/sessions"
"github.com/yosssi/ace"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"github.com/marianitadn/Hub/model"
//"./model"
)
const PRODUCTION_ENV = "production"
const DEVELOPMENT_ENV = "development"
type Context struct {
STORE *sessions.CookieStore
URL string
DB *mgo.Database
}
// App config
var ENV = Context{}
// GitHub credentials
var oauthCfg = &oauth.Config{}
func setEnv() {
var MONGO_URL, SECRET, URL string
if os.Getenv("GOENV") == PRODUCTION_ENV {
// Get vars from ENV
URL = ":" + os.Getenv("PORT")
MONGO_URL = os.Getenv("MONGO_URL")
SECRET = os.Getenv("SESSION_SECRET")
oauthCfg.ClientId = os.Getenv("GH_ID")
oauthCfg.ClientSecret = os.Getenv("GH_SECRET")
oauthCfg.AuthURL = "https://github.com/login/oauth/authorize"
oauthCfg.TokenURL = "https://github.com/login/oauth/access_token"
oauthCfg.RedirectURL = "https://xphub.herokuapp.com/logged"
//oauthCfg.RedirectURL = "http://localhost:3000/logged"
} else {
URL = "localhost:3000"
MONGO_URL = "localhost/hub"
SECRET = "big-secret-here"
}
// Try mongoDB connection
mongo, err := mgo.Dial(MONGO_URL)
if err != nil {
log.Fatalln("Cannot reach mongoDB: ", err)
os.Exit(1)
}
ENV.URL = URL
ENV.STORE = sessions.NewCookieStore([]byte(SECRET))
ENV.DB = mongo.DB("hub")
}
func main() {
// Set Environment variables
setEnv()
mux := mux.NewRouter()
mux.HandleFunc("/", index)
mux.HandleFunc("/login", HandleLogin)
mux.HandleFunc("/login/{user}", HandleDevLogin)
mux.HandleFunc("/logged", HandleGitHubLoginResponse)
mux.HandleFunc("/logout", HandleLogout)
mux.HandleFunc("/{user}/profile", HandleUserProfile)
mux.PathPrefix("/").Handler(http.FileServer(http.Dir("./static/")))
mux.HandleFunc("/{*}", Handle404)
log.Println("App started at:", ENV.URL)
http.ListenAndServe(ENV.URL, mux)
}
func index(w http.ResponseWriter, r *http.Request) {
// Get session info
session, _ := ENV.STORE.Get(r, "session")
log.Println(session.Values["user"])
// Get template
tpl, err := ace.Load("views/base", "views/index", nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
data := map[string]interface{}{
"Title": "index page",
"User": session.Values["user"],
"Msgs": []string{"1", "2", "3"},
"Map": map[string]int{
"ceva": 0,
},
}
if err := tpl.Execute(w, data); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func HandleLogin(w http.ResponseWriter, r *http.Request) {
// Go to GitHub Authentication page
url := oauthCfg.AuthURL + "?client_id=" + oauthCfg.ClientId
url += "&redirect_uri=" + oauthCfg.RedirectURL
// Redirect user to that page
http.Redirect(w, r, url, http.StatusFound)
}
func HandleDevLogin(w http.ResponseWriter, r *http.Request) {
// Get user from URL
user := mux.Vars(r)["user"]
// Save username to session
session, _ := ENV.STORE.Get(r, "session")
// Set some session values.
session.Values["user"] = user
// Save it
session.Save(r, w)
// Redirect user to index
http.Redirect(w, r, "/", http.StatusFound)
}
func HandleLogout(w http.ResponseWriter, r *http.Request) {
// Get user session and delete it
session, _ := ENV.STORE.Get(r, "session")
delete(session.Values, "user")
_ = session.Save(r, w)
// Redirect user to that page
http.Redirect(w, r, "/", http.StatusFound)
}
func HandleUserProfile(w http.ResponseWriter, r *http.Request) {
// Get session info
session, _ := ENV.STORE.Get(r, "session")
// Get user from db
user := model.User{}
collection := ENV.DB.C("users")
err := collection.Find(bson.M{"username":session.Values["user"]}).One(&user)
if err != nil {
log.Fatalln("Cannot get user profile: ", err)
os.Exit(1)
}
// Get all user repos
repos := []model.Repo{}
collection = ENV.DB.C("repos")
err = collection.Find(bson.M{"user":session.Values["user"]}).All(&repos)
if err != nil {
log.Fatalln("Cannot get user repos: ", err)
os.Exit(1)
}
// Get template
tpl, err := ace.Load("views/base", "views/profile", nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
data := map[string]interface{}{
"Title": "profile page",
"User": user,
"Repos": repos,
}
if err := tpl.Execute(w, data); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func HandleGitHubLoginResponse(w http.ResponseWriter, r *http.Request) {
// Get the code from the response
code := r.FormValue("code")
// Build token url
token_url := oauthCfg.TokenURL + "?client_id=" + oauthCfg.ClientId
token_url += "&client_secret=" + oauthCfg.ClientSecret + "&code=" + code
res, _ := http.Post(token_url, "application/json", nil)
response, _ := ioutil.ReadAll(res.Body)
// Parse response and get access token
m, _ := url.ParseQuery(string(response))
access_token := m["access_token"][0]
// Init octokit
t := &oauth.Transport{
Token: &oauth.Token{AccessToken: access_token},
}
client := github.NewClient(t.Client())
// Get current user info
userinfo, _, err := client.Users.Get("")
if err != nil {
log.Println("GitHub API call error for user info: ", err)
os.Exit(1)
}
// Add user to db
collection := ENV.DB.C("users")
doc := model.User{
ID: int(*userinfo.ID),
Avatar: string(*userinfo.AvatarURL),
Username: string(*userinfo.Login),
Fullname: string(*userinfo.Name),
Followers: int(*userinfo.Followers),
Following: int(*userinfo.Following),
}
_, err = collection.UpsertId(doc.ID, doc)
if err != nil {
log.Println("Could not add user: ", err)
os.Exit(1)
}
// Save username to session
session, _ := ENV.STORE.Get(r, "session")
// Set some session values.
session.Values["user"] = string(*userinfo.Login)
// Save it
session.Save(r, w)
// Update user repos
go updateRepos(string(*userinfo.Login), access_token)
// Redirect to index
http.Redirect(w, r, "/", http.StatusFound)
}
func Handle404(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("404: Page not found. Go away!"))
}
//// CONTROLERS ////
func updateRepos(user string, access_token string) {
// Init octokit
t := &oauth.Transport{
Token: &oauth.Token{AccessToken: access_token},
}
client := github.NewClient(t.Client())
// Request all repositories for the authenticated user
repos, _, err := client.Repositories.List("", nil)
if err != nil {
log.Println("GitHub API call error for user repos: ", err)
os.Exit(1)
}
// Get all repositories from db
collection := ENV.DB.C("repos")
var known_repos []model.Repo
err = collection.Find(bson.M{"user": string(user)}).All(&known_repos)
if err != nil {
log.Println("Failed to get repos from db: ", err)
os.Exit(1)
}
// Push public repos to db
for _, repo := range repos {
if (! *repo.Private) {
var repo_language = ""
if repo.Language != nil {
repo_language = *repo.Language
}
doc := model.Repo{
ID: int(*repo.ID),
Name: string(*repo.Name),
User: string(user),
Owner: string(*repo.Owner.Login),
URL: string(*repo.HTMLURL),
Description: string(*repo.Description),
Fork: bool(*repo.Fork),
Language: repo_language,
Stars: int(*repo.StargazersCount),
Watchers: int(*repo.WatchersCount),
Forks: int(*repo.ForksCount),
}
// Compare to known repos and detect changes or new ones
var found = false
for _, repo := range known_repos {
if doc == repo {
found = true
}
}
// Upload changes
if !found {
_, err := collection.UpsertId(doc.ID, doc)
if err != nil {
log.Println("Could not upsert repo: ", err)
os.Exit(1)
}
}
}
}
}