Skip to content

Commit

Permalink
Replace raw sql with gorm ORM
Browse files Browse the repository at this point in the history
  • Loading branch information
Lukas Matt committed Feb 26, 2018
1 parent d94db2f commit fa0f1a4
Show file tree
Hide file tree
Showing 7 changed files with 116 additions and 77 deletions.
16 changes: 10 additions & 6 deletions authentication.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ import (
"net/http"
"golang.org/x/oauth2"
"github.com/google/go-github/github"
"database/sql"
_ "github.com/mattn/go-sqlite3"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"context"
"strings"
)
Expand All @@ -33,7 +33,7 @@ func authentication(w http.ResponseWriter, r *http.Request) {
accessToken := r.URL.Query().Get("access_token")
repo := r.URL.Query().Get("repo")
if accessToken != "" && repo != "" {
db, err := sql.Open("sqlite3", "./server.db")
db, err := gorm.Open(databaseDriver, databaseDSN)
if err != nil {
logger.Println(err)
fmt.Fprintf(w, "Database Failure :(")
Expand All @@ -56,9 +56,13 @@ func authentication(w http.ResponseWriter, r *http.Request) {
}

secret := Secret(16)
_, err = db.Exec(fmt.Sprintf(`insert into repos(slug, token, secret)
values('%s', '%s', '%s');`, repo, accessToken, secret,
)); if err != nil {
repo := Repo{
Slug: repo,
Token: accessToken,
Secret: secret,
}
err = db.Create(&repo).Error
if err != nil {
logger.Println(err)
fmt.Fprintf(w, "Database Insert Failure :(\n%s",
"(the project probably already exists)")
Expand Down
40 changes: 40 additions & 0 deletions build.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
//
// TheFederation Github Integration Server
// Copyright (C) 2018 Lukas Matt <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package main

import (
"github.com/jinzhu/gorm"
)

type Build struct {
gorm.Model
RepoID int
Matrix string
TravisType string
TravisRequestID int64
TravisRepositoryID int64
PRUser string
PRRepo string
PRSha string

Repo Repo
}

func (build *Build) AfterFind(db *gorm.DB) error {
return db.Model(build).Related(&build.Repo).Error
}
26 changes: 0 additions & 26 deletions database.go

This file was deleted.

25 changes: 7 additions & 18 deletions frontend.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,39 +19,28 @@ package main

import (
"net/http"
"database/sql"
_ "github.com/mattn/go-sqlite3"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"fmt"
)

func frontend(w http.ResponseWriter, r *http.Request) {
db, err := sql.Open("sqlite3", "./server.db")
db, err := gorm.Open(databaseDriver, databaseDSN)
if err != nil {
logger.Println(err)
fmt.Fprintf(w, "Database Error :(")
return
}
defer db.Close()

rows, err := db.Query("select slug from repos")
var repos Repos
err = db.Find(&repos).Error
if err != nil {
logger.Println(err)
fmt.Fprintf(w, "Database Query Error :(")
return
}
defer rows.Close()

var slugs []string
for rows.Next() {
var slug string
err = rows.Scan(&slug)
if err != nil {
logger.Println(err)
fmt.Fprintf(w, "Database Scan Error :(")
continue
}
slugs = append(slugs, slug)
}
fmt.Fprintf(w, `<!DOCTYPE html>
<html>
<head>
Expand All @@ -77,15 +66,15 @@ func frontend(w http.ResponseWriter, r *http.Request) {
</tr>
</thead>
<tbody>`)
for i, slug := range slugs {
for i, repo := range repos {
fmt.Fprintf(w, `
<tr>
<th scope="row">%d</th>
<td>%s</td>
<td>
<a href="https://github.com/%s">Details</a>
</td>
</tr>`, i+1, slug, slug)
</tr>`, i+1, repo.Slug, repo.Slug)
}
fmt.Fprintf(w, `
</tbody>
Expand Down
31 changes: 31 additions & 0 deletions repo.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
//
// TheFederation Github Integration Server
// Copyright (C) 2018 Lukas Matt <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package main

import (
"github.com/jinzhu/gorm"
)

type Repo struct {
gorm.Model
Slug string
Token string
Secret string
}

type Repos []Repo
25 changes: 13 additions & 12 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,15 @@ import (
oauth2Github "golang.org/x/oauth2/github"
"time"
"math/rand"
"database/sql"
_ "github.com/mattn/go-sqlite3"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"flag"
"os"
)

var (
databaseDriver = "sqlite3"
databaseDSN = "./server.db"
logger = log.New(os.Stdout, "", log.Ldate | log.Ltime | log.Lmicroseconds | log.Lshortfile)
runes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
travisToken, serverDomain string
Expand All @@ -53,20 +55,19 @@ func init() {
flag.StringVar(&conf.ClientSecret, "github-secret", "",
"Specify the github client secret (required)")

db, err := sql.Open("sqlite3", "./server.db")
db, err := gorm.Open(databaseDriver, databaseDSN)
if err != nil {
panic(err)
panic("failed to connect database")
}
defer db.Close()

_, err = db.Exec(`create table repos(slug text, token text, secret text);`)
if err != nil {
logger.Println(err)
}
_, err = db.Exec(`create unique index index_on_repos_slug on repos(slug);`)
if err != nil {
logger.Println(err)
}
build := &Build{}
db.Model(build).AddUniqueIndex("index_builds_on_repo_id_and_matrix", "repo_id", "matrix")
db.AutoMigrate(build)

repo := &Repo{}
db.Model(repo).AddUniqueIndex("index_repos_on_slug", "slug")
db.AutoMigrate(repo)
}

func Secret(n int) string {
Expand Down
30 changes: 15 additions & 15 deletions webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,20 @@ import (
"github.com/google/go-github/github"
"io/ioutil"
"encoding/json"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)

func webhook(w http.ResponseWriter, r *http.Request) {
db, err := gorm.Open(databaseDriver, databaseDSN)
if err != nil {
logger.Println(err)
fmt.Fprintf(w, `{"error":"database error"}`)
return
}
defer db.Close()
defer r.Body.Close()

b, err := ioutil.ReadAll(r.Body)
if err != nil {
logger.Println(err)
Expand All @@ -50,34 +60,24 @@ func webhook(w http.ResponseWriter, r *http.Request) {
return
}

var secret string
err = query(fmt.Sprintf("select secret from repos where slug like '%s';",
*pr.Base.Repo.FullName), &secret)
var repo Repo
err = db.Where("slug = ?", *pr.Base.Repo.FullName).Find(&repo).Error
if err != nil {
logger.Println(err, *pr.Base.Repo.FullName)
fmt.Fprintf(w, `{"error":"repo not registered"}`)
return
}

// XXX validate payload
//_, err = github.ValidatePayload(r, []byte(secret))
//_, err = github.ValidatePayload(r, []byte(repo.Secret))
//if err != nil {
// logger.Println(err, secret)
// logger.Println(err, repo.Secret)
// fmt.Fprintf(w, `{"error":"invalid signature"}`)
// return
//}

var token string
err = query(fmt.Sprintf("select token from repos where slug like '%s'",
*pr.Base.Repo.FullName), &token)
if err != nil {
logger.Println(err, *pr.Base.Repo.FullName)
fmt.Fprintf(w, `{"error":"repo not registered"}`)
return
}

var request TravisRequest
go request.Run(token,
go request.Run(repo.Token,
[]string{fmt.Sprintf(
`"PRREPO=%s PRSHA=%s"`,
*pr.Head.Repo.CloneURL,
Expand Down

0 comments on commit fa0f1a4

Please sign in to comment.