Skip to content

Commit

Permalink
Subdomain
Browse files Browse the repository at this point in the history
  • Loading branch information
farazfazli committed Jan 24, 2016
1 parent 6bde166 commit 3791bdc
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 128 deletions.
Binary file modified GoBlog
Binary file not shown.
8 changes: 4 additions & 4 deletions create.sh
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
#!/bin/bash
# Script written by Faraz
# Automates creating a new Journey Blog with nginx
SITENAME="$1" # Site Name (Without URL)
SITEURL="$2" # Site URL excluding http:// or www.
PORT="$3" # <- Random port passed in
if [ -z "$SITENAME" ] || [ -z "$SITEURL" ] || [ -z "$PORT" ]
SITENAME="$1" # <- Subdomain
PORT="$2" # <- Random port passed in
if [ -z "$SITENAME" ] || [ -z "$PORT" ]
then
echo 'Error, not enough arguments!'
exit 2
fi
SITEURL=$SITENAME.goghost.pw
SITENAME=journey-$SITENAME
mkdir -p /var/www/$SITENAME
cd /var/www/$SITENAME
Expand Down
129 changes: 15 additions & 114 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,29 +1,19 @@
package main

import (
"encoding/json"
"fmt"
"html/template"
"log"
"math/rand"
"net/http"
"net/url"
"os/exec"
"regexp"
"strconv"
"time"

"github.com/boltdb/bolt"
"github.com/julienschmidt/httprouter"
)

const DEBUG bool = false

type BlogDetails struct {
Blogname string `json:"blogname"`
Website string `json:"website"`
}

// TODO add bcrypt

func init() {
Expand Down Expand Up @@ -56,13 +46,6 @@ func init() {
}
return nil
})
db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte("UserToBlog")) // user -> blogdetails
if err != nil {
return fmt.Errorf("Error with UserToBlog: %s", err)
}
return nil
})
}

func LoginPage(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
Expand All @@ -82,7 +65,7 @@ func LoginHandler(w http.ResponseWriter, req *http.Request, p httprouter.Params)
if verifyUser(w, req, email, password) {
http.Redirect(w, req, "/admin/", http.StatusFound)
} else {
http.Redirect(w, req, "/error/Invalid email or password", http.StatusFound)
fmt.Fprintf(w, "Invalid email/password")
}
}

Expand Down Expand Up @@ -116,17 +99,6 @@ func MainPage(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
})
}

func ErrorPage(w http.ResponseWriter, r *http.Request, pm httprouter.Params) {
baseT := template.Must(template.New("base").Parse(base))
baseT = template.Must(baseT.Parse(errorPage))

baseT.ExecuteTemplate(w, "base", map[string]string{
"PageName": "error",
"User": getUser(w, r),
"Error": pm.ByName("errorcode"),
})
}

func SignupPage(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
baseT := template.Must(template.New("base").Parse(base))
baseT = template.Must(baseT.Parse(signup))
Expand Down Expand Up @@ -168,45 +140,27 @@ func SignupHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params)
}

func AdminPage(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
username := getUser(w, r)
if username != "" {
db, err := bolt.Open("goblog.db", 0600, nil)
if err != nil {
fmt.Println(err)
}
defer db.Close()
if getUser(w, r) != "" {

baseT := template.Must(template.New("base").Parse(base))
baseT = template.Must(baseT.Parse(admin))

baseT.ExecuteTemplate(w, "base", map[string]interface{}{
baseT.ExecuteTemplate(w, "base", map[string]string{
"PageName": "admin",
"User": username,
"Blogs": getBlogsForUser(db, username),
"User": getUser(w, r),
})
} else {
http.Redirect(w, r, "/error/You must be authenticated!", http.StatusFound)
fmt.Fprintf(w, "You must be authenticated!") // TODO make this look better
}
}

func AdminHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
blogname := r.FormValue("blogname")
websiteOriginal := r.FormValue("website")
blogname := r.FormValue("blogname") // <- subdomain
website := blogname + ".goblog.pw" // Change this
port := rand.Intn(63000) + 2000

website, err := checkUrl(websiteOriginal)
if err != nil {
http.Redirect(w, r, fmt.Sprintf("/error/%s is not a valid url", websiteOriginal), http.StatusFound)
return
}

re := regexp.MustCompile("[^A-Za-z]")
blogname = re.ReplaceAllString(blogname, "")

blogcheck := []byte("")

username := getUser(w, r)
if username != "" {
if getUser(w, r) != "" {
db, err := bolt.Open("goblog.db", 0600, nil)
if err != nil {
fmt.Println(err)
Expand All @@ -217,69 +171,27 @@ func AdminHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params)
blogcheck = b.Get([]byte(blogname))
return nil
})

if blogcheck == nil {
create, err := exec.Command("./create.sh", blogname, website, strconv.Itoa(port)).Output()
if err != nil && !DEBUG {
create, err := exec.Command("./create.sh", blogname, strconv.Itoa(port)).Output()
if err != nil {
fmt.Println(err)
} else {
fmt.Println("80 -> " + strconv.Itoa(port))
fmt.Println(create)
fmt.Fprintf(w, "%s", create)
db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("BlogMappingBucket"))
err := b.Put([]byte(blogname), []byte(website))
b := tx.Bucket([]byte("UsersBucket"))
err := b.Put([]byte(blogname), []byte(website)) // <- TODO change this
return err
})
addBlogToUser(db, username, blogname, website)
http.Redirect(w, r, "/admin/", http.StatusFound)
return
}
} else {
http.Redirect(w, r, "/error/Failure creating blog! Please choose a different name!", http.StatusFound)
return
fmt.Fprintf(w, "Failure creating blog! Please choose a different name!")
}
} else {
http.Redirect(w, r, "/error/You must be authenticated!", http.StatusFound)
return
fmt.Fprintf(w, "You must be authenticated!") // TODO make this look better
}
}

func addBlogToUser(db *bolt.DB, username string, blogname string, website string) {
existingblogs := []byte("")

db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("UserToBlog"))
existingblogs = b.Get([]byte(username))
return nil
})

var v []BlogDetails = make([]BlogDetails, 0)
json.Unmarshal(existingblogs, &v)

db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("UserToBlog"))
v = append(v, BlogDetails{blogname, website})
m, _ := json.Marshal(v)
err := b.Put([]byte(username), m)
return err
})
}

func getBlogsForUser(db *bolt.DB, username string) []BlogDetails {
existingblogs := []byte("")

db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("UserToBlog"))
existingblogs = b.Get([]byte(username))
return nil
})

var v []BlogDetails = make([]BlogDetails, 0)
json.Unmarshal(existingblogs, &v)

return v
}

func verifyUser(w http.ResponseWriter, r *http.Request, email string, password string) bool {
correctpass := []byte("")
db, err := bolt.Open("goblog.db", 0600, nil)
Expand Down Expand Up @@ -393,16 +305,6 @@ func getUserFromCookie(value string) string {
return ""
}

func checkUrl(s string) (string, error) {
u, err := url.Parse(s)

if err != nil || u.Host == "" {
u, err = url.Parse("http://" + s)
}

return u.Host, err
}

func main() {
fmt.Println("Started server on port 1337")
router := httprouter.New()
Expand All @@ -413,6 +315,5 @@ func main() {
router.GET("/admin/", AdminPage)
router.POST("/admin/", AdminHandler)
router.GET("/logout/", LogoutHandler)
router.GET("/error/:errorcode/", ErrorPage)
log.Fatal(http.ListenAndServe(":1337", router))
}
11 changes: 1 addition & 10 deletions pages.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,22 +135,13 @@ var admin = `
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="blog">Blog Name</label>
<label class="col-md-4 control-label" for="blog">Blog Name/Subdomain (.ghost.pw)</label>
<div class="col-md-6">
<input id="blogname" name="blogname" type="text" placeholder="exampleblog" class="form-control input-md" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="website">Blog Website</label>
<div class="col-md-6">
<input id="blogname" name="website" type="text" placeholder="example.com" class="form-control input-md" required="">
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="submit"></label>
Expand Down

0 comments on commit 3791bdc

Please sign in to comment.