Skip to content
This repository was archived by the owner on Jan 12, 2025. It is now read-only.

Commit b2fe7e8

Browse files
committed
Boosting title field for better relevancy + first stab at github oauth
1 parent a1bd4f5 commit b2fe7e8

1 file changed

Lines changed: 145 additions & 5 deletions

File tree

‎daemon/main.go‎

Lines changed: 145 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,33 +2,173 @@ package main
22

33
import (
44
"encoding/json"
5+
"errors"
6+
"flag"
57
"fmt"
68
log "github.com/cihub/seelog"
79
"github.com/crufter/borg/types"
10+
"github.com/google/go-github/github"
811
httpr "github.com/julienschmidt/httprouter"
9-
"github.com/olivere/elastic"
12+
"github.com/rs/cors"
13+
"github.com/ventu-io/go-shortid"
14+
"golang.org/x/oauth2"
15+
"gopkg.in/olivere/elastic.v2"
16+
"io/ioutil"
1017
"net/http"
1118
"reflect"
1219
"strconv"
1320
)
1421

22+
const (
23+
githubAccessURL = "https://github.com/login/oauth/access_token"
24+
)
25+
26+
var (
27+
githubClientId = flag.String("github-client-id", "", "Github oauth client id")
28+
githubClientSecret = flag.String("github-client-secret", "", "Github client secret")
29+
esAddr = flag.String("esaddr", "127.0.0.1:9200", "Elastic Search address")
30+
)
31+
1532
var (
16-
client *elastic.Client
33+
client *elastic.Client
34+
oauthCfg *oauth2.Config
1735
)
1836

37+
type Logger struct{}
38+
39+
func (l *Logger) Printf(str string, i ...interface{}) {
40+
fmt.Println(fmt.Sprintf(str, i...))
41+
}
42+
1943
func init() {
20-
cl, err := elastic.NewClient(elastic.SetSniff(false), elastic.SetURL("http://127.0.0.1:9200"))
44+
flag.Parse()
45+
l := Logger{}
46+
cl, err := elastic.NewClient(elastic.SetSniff(false), elastic.SetURL(fmt.Sprintf("http://%v", *esAddr)), elastic.SetTraceLog(&l))
2147
if err != nil {
2248
panic(err)
2349
}
2450
client = cl
2551
}
2652

2753
func main() {
54+
oauthCfg = &oauth2.Config{
55+
ClientID: *githubClientId,
56+
ClientSecret: *githubClientSecret,
57+
Endpoint: oauth2.Endpoint{
58+
AuthURL: githubAccessURL,
59+
},
60+
//RedirectURL: redirectUrl,
61+
Scopes: []string{"read:org"},
62+
}
2863
r := httpr.New()
2964
r.GET("/v1/query", query)
65+
r.POST("/v1/auth/github", githubAuth)
66+
handler := cors.Default().Handler(r)
3067
log.Info("Starting http server")
31-
log.Critical(http.ListenAndServe(fmt.Sprintf(":%v", 9992), r))
68+
log.Critical(http.ListenAndServe(fmt.Sprintf(":%v", 9992), handler))
69+
}
70+
71+
func githubAuth(w http.ResponseWriter, r *http.Request, p httpr.Params) {
72+
body, err := ioutil.ReadAll(r.Body)
73+
if err != nil {
74+
panic(err)
75+
}
76+
tkn, err := oauthCfg.Exchange(oauth2.NoContext, string(body))
77+
if err != nil {
78+
fmt.Fprintln(w, fmt.Sprintf("there was an issue getting your token: %v", err))
79+
return
80+
}
81+
if !tkn.Valid() {
82+
fmt.Fprintln(w, "retreived invalid token")
83+
return
84+
}
85+
client := github.NewClient(oauthCfg.Client(oauth2.NoContext, tkn))
86+
user, _, err := client.Users.Get("")
87+
if err != nil {
88+
fmt.Println(w, fmt.Sprintf("error getting name: %v", err))
89+
return
90+
}
91+
usr, err := readUser(*user.Email)
92+
if err != nil {
93+
fmt.Println(w, fmt.Sprintf("error getting user: %v", err))
94+
return
95+
}
96+
if usr == nil {
97+
usr, err = toUser(user)
98+
if err != nil {
99+
fmt.Println(w, fmt.Sprintf("error converting user: %v", err))
100+
return
101+
}
102+
err = registerUser(*usr)
103+
if err != nil {
104+
}
105+
}
106+
bs, err := json.Marshal(map[string]interface{}{
107+
"User": user,
108+
"Token": tkn.AccessToken,
109+
})
110+
if err != nil {
111+
panic(err)
112+
}
113+
fmt.Fprint(w, string(bs))
114+
}
115+
116+
type User struct {
117+
Id string
118+
Email string
119+
Name string
120+
}
121+
122+
func toUser(user *github.User) (*User, error) {
123+
switch {
124+
case user.Email == nil:
125+
return nil, errors.New("User has no email")
126+
case user.Name == nil:
127+
return nil, errors.New("User has no email")
128+
}
129+
id, err := shortid.Generate()
130+
if err != nil {
131+
return nil, err
132+
}
133+
ret := &User{
134+
Id: id,
135+
Email: *user.Email,
136+
Name: *user.Name,
137+
}
138+
return ret, nil
139+
}
140+
141+
func readUser(email string) (*User, error) {
142+
termQuery := elastic.NewTermQuery("email", email)
143+
res, err := client.Search().Index("borg").Type("user").Query(termQuery).From(0).Size(2).Do()
144+
if err != nil {
145+
return nil, err
146+
}
147+
var ttyp User
148+
users := []User{}
149+
for _, item := range res.Each(reflect.TypeOf(ttyp)) {
150+
if t, ok := item.(User); ok {
151+
users = append(users, t)
152+
}
153+
}
154+
switch {
155+
case len(users) == 0:
156+
return nil, errors.New("User not found with email " + email)
157+
case len(users) > 1:
158+
return nil, errors.New("Multiple users found with email " + email)
159+
}
160+
return &users[0], nil
161+
}
162+
163+
func registerUser(user User) error {
164+
_, err := client.Index().
165+
Index("borg").
166+
Type("user").
167+
Id(user.Id).
168+
BodyJson(user).
169+
Refresh(true).
170+
Do()
171+
return err
32172
}
33173

34174
func query(w http.ResponseWriter, r *http.Request, p httpr.Params) {
@@ -47,7 +187,7 @@ func query(w http.ResponseWriter, r *http.Request, p httpr.Params) {
47187
log.Infof("Querying '%v' with size '%v'", q, size)
48188
}
49189
res, err := client.Search().Index("borg").Type("problem").From(0).Size(size).Query(
50-
elastic.NewQueryStringQuery(q)).Do()
190+
elastic.NewMultiMatchQuery(q).FieldWithBoost("Title", 5.0).Field("Solutions.Body")).Do()
51191
if err != nil {
52192
panic(err)
53193
}

0 commit comments

Comments
 (0)