/src/main.go
Go | 2332 lines | 1652 code | 387 blank | 293 comment | 449 complexity | b4718ee88a93fb959b156dba5c1309ea MD5 | raw file
Large files files are truncated, but you can click here to view the full file
- package main
- import (
- "encoding/base64"
- "encoding/json"
- "fmt"
- "html/template"
- "log"
- // "flag"
- "net/http"
- "os"
- // "net/url"
- "path/filepath"
- "regexp"
- "strings"
- "bytes"
- "database/sql"
- "strconv"
- "io"
- "net"
- "mime"
- "io/ioutil"
- // "math/rand"
- // "reflect"
- auth "./authentication"
- db "./local_database"
- survey "./survey"
- "github.com/minio/minio-go"
- "github.com/badoux/checkmail"
- "github.com/fsnotify/fsnotify"
- "github.com/gorilla/mux"
- "github.com/gorilla/securecookie"
- "github.com/gorilla/websocket"
- "github.com/oxtoacart/bpool"
- uuid "github.com/satori/go.uuid"
- "gopkg.in/mgo.v2/bson"
- "github.com/rs/xid"
- "github.com/dpapathanasiou/go-recaptcha"
- "github.com/kirves/go-form-it" // import directly into this repo
- "github.com/kirves/go-form-it/fields"
- "github.com/gocraft/dbr"
- )
- var clients = make(map[*websocket.Conn]bool)
- var clientId = make(map[*websocket.Conn]string)
- var clientUser = make(map[*websocket.Conn]string)
- var broadcast = make(chan Message)
- // var socketClients = make(map[string], map[*websocket.Conn]bool)
- var upgrader = websocket.Upgrader{}
- var Global = 0 // For testing rooms functionality
- type Message struct {
- Id int `json:"id"`
- Email string `json:"email"`
- Username string `json:"username"`
- Message string `json:"message"`
- IsPublic bool `json:"isPublic"`
- Signature string `json:"signature"`
- Complete bool `json:"complete"`
- Creating bool `json:"creating"`
- Session string `json:"session"`
- OriginalQuestion int `json:"originalquestion"`
- IsTab bool `json:"isTab"`
- Tab int `json:"tab"`
- File string `json:"file"`
- Owner string `json:"owner"`
- Task map[string]interface{} `json:"task"`
- }
- type Answer struct {
- Question int `json:"question"`
- Response string `json:"response"`
- }
- type Course struct {
- Name string
- Description string `form_widget:"textarea"`
- Type string
- LessonsSections int `form_options:"skip"`
- TotalSections int `form_options:"skip"`
- Link string `form_options:"skip"`
- Difficulty int `form_options:"skip"`
- Catagory string
- IsPublic bool `form_label:"Is Public"`
- }
- type Task struct {
- Name string `json:"name"`
- Body string `json:"body"`
- IsPublic string `json:"isPublic"`
- OriginalQuestion int `json:"originalQuestion"`
- Complete bool `json:"complete"`
- Board string `json:"board"`
- Owner int `json:"owner"`
- Tab int `json:"tab"`
- Index int `json:"index"`
- }
- //Basic user Structure (translates into SQL model)
- type User struct {
- Email string `json:"email"`
- Username string `json:"username"`
- DisplayName string `json:"display_name"`
- }
- type PageTemplate struct {
- Main string
- }
- func main() {
- // Create simple fileserver
- r := mux.NewRouter()
- fs := http.FileServer(http.Dir("../public/static/"))
- loadTemplates()
- http.Handle("/", r)
- http.Handle("/static/", http.StripPrefix("/static/", fs))
- //Add log to file
- //https://stackoverflow.com/questions/19965795/go-golang-write-log-to-file
- // f, err := os.OpenFile("golog.log", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
- // if err != nil {
- // log.Fatalf("Error opening file: %v", err)
- // }
- // defer f.Close()
- // log.SetOutput(f)
- log.SetFlags(log.LstdFlags | log.Lshortfile)
- //Digital Ocean Spaces SDK
- endpoint := "s3.amazonaws.com"
- accessKeyID := "AKIAIWRI2VNGP4PCA2EA"
- secretAccessKey := "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"
- useSSL := true
- // Initialize minio client object.
- minioClient, err := minio.New(endpoint, accessKeyID, secretAccessKey, useSSL)
- if err != nil {
- log.Fatalln(err)
- }
-
- // Make a new bucket called mymusic.
- bucketName := "paariomain"
- location := "us-east-2"
- err = minioClient.MakeBucket(bucketName, location)
- if err != nil {
- // Check to see if we already own this bucket (which happens if you run this twice)
- exists, err := minioClient.BucketExists(bucketName)
- if err == nil && exists {
- log.Printf("We already own %s\n", bucketName)
- } else {
- log.Fatalln(err)
- }
- }
- log.Printf("Successfully created %s\n", bucketName)
- adminModels := map[string]interface{}{
- "course": Course{},
- "task": Task{},
- }
- recaptcha.Init ("6LfBNFwUAAAAANnttb-9nUX83ZZw4LrOTLKdAQiI")
- //survey.Load_Survey_Database()
- //For local testing
- db.Connect_To_Test_Database()
- survey.Load_Survey_Database()
- defer survey.MongoDatabase.Close()
- defer survey.QuestionDatabase.Close()
- defer db.MainDatabase.Close()
- r.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- renderTemplate(w, "404.html", nil, r)
- })
- r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
- currentUser := getUserName(r)
- if currentUser != "" {
- http.Redirect(w, r, "/app/dashboard/", http.StatusTemporaryRedirect)
- return
- }
- renderTemplate(w, "index.html", nil, r)
- })
- r.HandleFunc("/firebase-messaging-sw.js", func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Content-Type", "text/javascript; charset=utf-8")
- b, err := ioutil.ReadFile("firebase-messaging-sw.js") // just pass the file name
- if err != nil {
- fmt.Print(err)
- }
- fmt.Fprintf(w, string(b))
- })
- r.HandleFunc("/api/users/token/", func(w http.ResponseWriter, r *http.Request) {
- currentUser := getUserName(r)
- if currentUser == "" {
- fmt.Fprintf(w, `{"Error":"Not Authenticated"}`)
- return
- }
- userId := getUserId(r)
- token := r.FormValue("token")
- database := db.MainDatabase
- rows, err := database.Query(fmt.Sprintf("SELECT fb_token FROM device WHERE fb_token='%v';", token))
- if err != nil {
- log.Println(err)
- }
- defer rows.Close()
-
- var count = 0
- for rows.Next() {
- count += 1
- }
- if count > 0 {
- fmt.Fprintf(w, "{\"Error\":\"Already Added Token\"}")
- return
- }
- rows, err = database.Query(fmt.Sprintf("INSERT INTO device (auth_user, fb_token) VALUES (%v, '%v');", userId, token))
- if err != nil {
- log.Println(err)
- }
- defer rows.Close()
-
- for rows.Next() {
- continue
- }
- fmt.Fprintf(w, "{\"Success\":\"Added Token\"}")
- })
- r.HandleFunc("/register/signup/", func(w http.ResponseWriter, r *http.Request) {
- redirect := r.URL.Query().Get("redirect")
- renderTemplate(w, "sign_up.html", map[string]interface{}{
- "RedirectUrl": redirect,
- }, r)
- })
- r.HandleFunc("/admin/", func(w http.ResponseWriter, r *http.Request) {
- renderTemplate(w, "admin_home.html", nil, r)
- })
- r.HandleFunc("/terms/", func(w http.ResponseWriter, r *http.Request) {
- renderTemplate(w, "terms.html", nil, r)
- })
- r.HandleFunc("/privacy/", func(w http.ResponseWriter, r *http.Request) {
- renderTemplate(w, "privacy.html", nil, r)
- })
- r.HandleFunc("/about/", func(w http.ResponseWriter, r *http.Request) {
- renderTemplate(w, "about.html", nil, r)
- })
- r.HandleFunc("/contact/", func(w http.ResponseWriter, r *http.Request) {
- renderTemplate(w, "contact.html", nil, r)
- })
-
- r.HandleFunc("/api/board/edit/", func(w http.ResponseWriter, r *http.Request) {
- currentUser := getUserName(r)
- if currentUser == "" {
- fmt.Fprintf(w, `{"Error":"Not Authenticated"}`)
- return
- }
- userId := getUserId(r)
- name := r.FormValue("board_name")
- vision := r.FormValue("board_vision")
- boardId := r.FormValue("board_id")
- database := db.MainDatabase
- rows, err := database.Query(fmt.Sprintf("SELECT id FROM boards WHERE owner=%v AND id=%v;", userId, boardId))
- if err != nil {
- log.Println(err)
- }
- defer rows.Close()
-
- var count = 0
- for rows.Next() {
- count += 1
- }
- if count <= 0 {
- fmt.Fprintf(w, "{\"Error\":\"Not Board Owner\"}")
- return
- }
- insert_row, error := database.Query(fmt.Sprintf("UPDATE boards SET name='%v', vision='%v' WHERE id=%v;", name, vision, boardId))
- if error != nil {
- log.Fatal(error)
- }
- for insert_row.Next() {
- continue
- }
- fmt.Fprintf(w, "{\"Success\":\"Board changed\"}")
- })
- // r.HandleFunc("/app/", func(w http.ResponseWriter, r *http.Request) {
- // renderTemplate(w, "admin_home.html", nil, r)
- // })
- r.HandleFunc("/api/board/tabs/get/", func(w http.ResponseWriter, r *http.Request) {
- currentUser := getUserName(r)
- if currentUser == "" {
- fmt.Fprintf(w, `{"Error":"Not Authenticated"}`)
- return
- }
- userId := getUserId(r)
- tab := r.FormValue("tab")
- session := r.FormValue("board")
- database := db.MainDatabase
-
- rows, err := database.Query(fmt.Sprintf("SELECT task.id, task.timestamp, task.body, task.originalquestion, authentication_users.displayname, task.file FROM task JOIN boards ON boards.session=task.board JOIN authentication_users ON task.owner=authentication_users.id WHERE active=true AND isPublic=false AND complete=false AND boards.session='%v' AND tab=%v AND task.owner=%v ORDER BY task.timestamp desc;", session, tab, userId))
- if err != nil {
- log.Fatal(err)
- }
- cols, _ := rows.Columns()
- var mapList []map[string]interface{}
- notLast := rows.Next()
- for notLast {
- // Create a slice of interface{}'s to represent each column,
- // and a second slice to contain pointers to each item in the columns slice.
- columns := make([]interface{}, len(cols))
- columnPointers := make([]interface{}, len(cols))
- for i, _ := range columns {
- columnPointers[i] = &columns[i]
- }
-
- // Scan the result into the column pointers...
- if err := rows.Scan(columnPointers...); err != nil {
-
- }
- // Create our map, and retrieve the value for each column from the pointers slice,
- // storing it in the map with the name of the column as the key.
- m := make(map[string]interface{})
- for i, colName := range cols {
- val := columnPointers[i].(*interface{})
- m[colName] = *val
-
-
- }
- notLast = rows.Next()
-
- // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
- //fmt.Println(m)
-
- queryStr := fmt.Sprintf(`SELECT authentication_users.displayname FROM task JOIN task AS task_2 ON task_2.id=task.originalquestion FULL OUTER JOIN authentication_users ON authentication_users.id = task.owner WHERE task.complete = true AND (task.originalquestion=%v OR task_2.id=%v);`, m["originalquestion"], m["id"])
-
- if (m["originalquestion"] == nil) {
- queryStr = fmt.Sprintf(`SELECT authentication_users.displayname FROM task JOIN task AS task_2 ON task_2.id=task.originalquestion FULL OUTER JOIN authentication_users ON authentication_users.id = task.owner WHERE task.complete = true AND (task_2.id=%v);`, m["id"])
- }
- completed_rows, err := database.Query(queryStr)
- if err != nil {
- log.Fatal(err)
- }
- mapOfCompleted := getColumnMap(completed_rows)
- m["completed"] = mapOfCompleted
- // m["body"] = template.HTML(m["body"].(string))
- mapList = append(mapList, m)
- }
-
- jsonStr, err := json.Marshal(mapList)
- if err != nil {
- log.Fatal(err)
- }
- privateString := string(jsonStr)
- rows.Close()
- rows, err = database.Query(fmt.Sprintf("SELECT task.id, task.body, task.timestamp, task.originalquestion, authentication_users.displayname, task.file FROM task JOIN boards ON boards.session=task.board JOIN authentication_users ON task.owner=authentication_users.id WHERE active=true AND isPublic=false AND complete=true AND boards.session='%v' AND tab=%v AND task.owner=%v ORDER BY task.timestamp desc;", session, tab, userId))
- if err != nil {
- log.Fatal(err)
- }
- cols, _ = rows.Columns()
- var mapListComplete []map[string]interface{}
- notLast = rows.Next()
- for notLast {
- // Create a slice of interface{}'s to represent each column,
- // and a second slice to contain pointers to each item in the columns slice.
- columns := make([]interface{}, len(cols))
- columnPointers := make([]interface{}, len(cols))
- for i, _ := range columns {
- columnPointers[i] = &columns[i]
- }
-
- // Scan the result into the column pointers...
- if err := rows.Scan(columnPointers...); err != nil {
-
- }
- // Create our map, and retrieve the value for each column from the pointers slice,
- // storing it in the map with the name of the column as the key.
- m := make(map[string]interface{})
- for i, colName := range cols {
- val := columnPointers[i].(*interface{})
- m[colName] = *val
-
-
- }
- notLast = rows.Next()
-
- // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
- //fmt.Println(m)
-
- queryStr := fmt.Sprintf(`SELECT authentication_users.displayname FROM task JOIN task AS task_2 ON task_2.id=task.originalquestion FULL OUTER JOIN authentication_users ON authentication_users.id = task.owner WHERE task.complete = true AND (task.originalquestion=%v OR task_2.id=%v);`, m["originalquestion"], m["id"])
-
- if (m["originalquestion"] == nil) {
- queryStr = fmt.Sprintf(`SELECT authentication_users.displayname FROM task JOIN task AS task_2 ON task_2.id=task.originalquestion FULL OUTER JOIN authentication_users ON authentication_users.id = task.owner WHERE task.complete = true AND (task_2.id=%v);`, m["id"])
- }
- completed_rows, err := database.Query(queryStr)
- if err != nil {
- log.Fatal(err)
- }
- mapOfCompleted := getColumnMap(completed_rows)
- m["completed"] = mapOfCompleted
- // m["body"] = template.HTML(m["body"].(string))
- mapListComplete = append(mapListComplete, m)
- }
-
- jsonStr, err = json.Marshal(mapListComplete)
- if err != nil {
- log.Fatal(err)
- }
- completeString := string(jsonStr)
- rows.Close()
- rows, err = database.Query(fmt.Sprintf("SELECT task.id, task.body, task.timestamp, task.originalquestion, authentication_users.displayname, task.file FROM task JOIN boards ON boards.session=task.board JOIN authentication_users ON task.owner=authentication_users.id WHERE active=true AND isPublic=true AND boards.session='%v' AND tab=%v ORDER BY task.timestamp desc;", session, tab))
- if err != nil {
- log.Fatal(err)
- }
- cols, _ = rows.Columns()
- var mapListPublic []map[string]interface{}
- notLast = rows.Next()
- for notLast {
- // Create a slice of interface{}'s to represent each column,
- // and a second slice to contain pointers to each item in the columns slice.
- columns := make([]interface{}, len(cols))
- columnPointers := make([]interface{}, len(cols))
- for i, _ := range columns {
- columnPointers[i] = &columns[i]
- }
-
- // Scan the result into the column pointers...
- if err := rows.Scan(columnPointers...); err != nil {
-
- }
- // Create our map, and retrieve the value for each column from the pointers slice,
- // storing it in the map with the name of the column as the key.
- m := make(map[string]interface{})
- for i, colName := range cols {
- val := columnPointers[i].(*interface{})
- m[colName] = *val
- }
- notLast = rows.Next()
-
- // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
- //fmt.Println(m)
-
- queryStr := fmt.Sprintf(`SELECT authentication_users.displayname FROM task JOIN task AS task_2 ON task_2.id=task.originalquestion FULL OUTER JOIN authentication_users ON authentication_users.id = task.owner WHERE task.complete = true AND (task.originalquestion=%v OR task_2.id=%v);`, m["originalquestion"], m["id"])
-
- if (m["originalquestion"] == nil) {
- queryStr = fmt.Sprintf(`SELECT authentication_users.displayname FROM task JOIN task AS task_2 ON task_2.id=task.originalquestion FULL OUTER JOIN authentication_users ON authentication_users.id = task.owner WHERE task.complete = true AND (task_2.id=%v);`, m["id"])
- }
- completed_rows, err := database.Query(queryStr)
- if err != nil {
- log.Fatal(err)
- }
- mapOfCompleted := getColumnMap(completed_rows)
- m["completed"] = mapOfCompleted
- // m["body"] = template.HTML(m["body"].(string))
- mapListPublic = append(mapListPublic, m)
- }
- jsonStr, err = json.Marshal(mapListPublic)
- if err != nil {
- log.Fatal(err)
- }
- publicString := string(jsonStr)
- rows.Close()
- fmt.Fprintf(w, `{"Success": {"private": %v, "public": %v, "complete": %v}}`, privateString, publicString, completeString)
- })
- r.HandleFunc("/app/board/", func(w http.ResponseWriter, r *http.Request) {
- database := db.MainDatabase
- rows, err := database.Query("SELECT id, name, body FROM task WHERE isPublic=true ORDER BY task.timestamp desc;")
- if err != nil {
- log.Fatal(err)
- }
- cols, _ := rows.Columns()
- var mapList []map[string]interface{}
- for rows.Next() {
- // Create a slice of interface{}'s to represent each column,
- // and a second slice to contain pointers to each item in the columns slice.
- columns := make([]interface{}, len(cols))
- columnPointers := make([]interface{}, len(cols))
- for i, _ := range columns {
- columnPointers[i] = &columns[i]
- }
-
- // Scan the result into the column pointers...
- if err := rows.Scan(columnPointers...); err != nil {
-
- }
-
- // Create our map, and retrieve the value for each column from the pointers slice,
- // storing it in the map with the name of the column as the key.
- m := make(map[string]interface{})
- for i, colName := range cols {
- val := columnPointers[i].(*interface{})
- m[colName] = *val
- }
-
- // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
- //fmt.Println(m)
- mapList = append(mapList, m)
- }
- rows.Close()
- rows, err = database.Query("SELECT id, name, body, originalquestion FROM task WHERE isPublic=false AND complete=false ORDER BY task.timestamp desc;")
- if err != nil {
- log.Fatal(err)
- }
- defer rows.Close()
- cols, _ = rows.Columns()
- var mapListPrivate []map[string]interface{}
- for rows.Next() {
- // Create a slice of interface{}'s to represent each column,
- // and a second slice to contain pointers to each item in the columns slice.
- columns := make([]interface{}, len(cols))
- columnPointers := make([]interface{}, len(cols))
- for i, _ := range columns {
- columnPointers[i] = &columns[i]
- }
-
- // Scan the result into the column pointers...
- if err := rows.Scan(columnPointers...); err != nil {
-
- }
-
- // Create our map, and retrieve the value for each column from the pointers slice,
- // storing it in the map with the name of the column as the key.
- m := make(map[string]interface{})
- for i, colName := range cols {
- val := columnPointers[i].(*interface{})
- m[colName] = *val
- }
-
- // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
- //fmt.Println(m)
- mapListPrivate = append(mapListPrivate, m)
- }
- rows.Close()
- rows, err = database.Query("SELECT id, name, body, originalquestion FROM task WHERE isPublic=false AND complete=true ORDER BY task.timestamp desc;")
- if err != nil {
- log.Fatal(err)
- }
- defer rows.Close()
- cols, _ = rows.Columns()
- var mapListComplete []map[string]interface{}
- for rows.Next() {
- // Create a slice of interface{}'s to represent each column,
- // and a second slice to contain pointers to each item in the columns slice.
- columns := make([]interface{}, len(cols))
- columnPointers := make([]interface{}, len(cols))
- for i, _ := range columns {
- columnPointers[i] = &columns[i]
- }
-
- // Scan the result into the column pointers...
- if err := rows.Scan(columnPointers...); err != nil {
-
- }
-
- // Create our map, and retrieve the value for each column from the pointers slice,
- // storing it in the map with the name of the column as the key.
- m := make(map[string]interface{})
- for i, colName := range cols {
- val := columnPointers[i].(*interface{})
- m[colName] = *val
- }
-
- // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
- //fmt.Println(m)
- mapListComplete = append(mapListComplete, m)
- }
- taskForm := forms.BaseForm(forms.POST, "").SetId("taskForm").SetParam("name", "taskForm").Elements(
- fields.TextAreaField("Body", 30, 50).AddClass("materialize-textarea").SetLabel("Body"),
- fields.SubmitButton("submit", "Submit").AddClass("waves-effect waves-light btn"),
- )
- renderTemplate(w, "board_index.html", map[string]interface{}{"taskForm": taskForm, "publicTasks": mapList, "privateTasks": mapListPrivate, "completeTasks": mapListComplete}, r)
- })
- r.HandleFunc("/app/boards/{session}/", func(w http.ResponseWriter, r *http.Request) {
- vars := mux.Vars(r)
- session := vars["session"]
- currentUser := getUserName(r)
- if currentUser == "" {
- http.Redirect(w, r, fmt.Sprintf("/register/login/?redirect=/app/boards/%v/", session), http.StatusTemporaryRedirect)
- return
- }
- database := db.MainDatabase
- rows, err := database.Query(fmt.Sprintf("SELECT * FROM boards WHERE session='%v';", session))
- if err != nil {
- log.Println(err)
- }
- cols, _ := rows.Columns()
-
- var mapListBoard []map[string]interface{}
- for rows.Next() {
- // Create a slice of interface{}'s to represent each column,
- // and a second slice to contain pointers to each item in the columns slice.
- columns := make([]interface{}, len(cols))
- columnPointers := make([]interface{}, len(cols))
- for i, _ := range columns {
- columnPointers[i] = &columns[i]
- }
-
- // Scan the result into the column pointers...
- if err := rows.Scan(columnPointers...); err != nil {
-
- }
-
- // Create our map, and retrieve the value for each column from the pointers slice,
- // storing it in the map with the name of the column as the key.
- m := make(map[string]interface{})
- for i, colName := range cols {
- val := columnPointers[i].(*interface{})
- m[colName] = *val
- }
-
- // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
- //fmt.Println(m)
- mapListBoard = append(mapListBoard, m)
- }
- userId := getUserId(r)
- password := r.FormValue("password")
- rows, err = database.Query(fmt.Sprintf("SELECT user_boards.id FROM user_boards JOIN boards ON boards.id=user_boards.boards WHERE boards.session='%v' AND (user_boards.auth_user=%v OR boards.password='%v');", session, userId, password))
- if err != nil {
- log.Println(err)
- }
- defer rows.Close()
- var count = 0
- for rows.Next() {
- count += 1
- }
- if count <= 0 {
- http.Redirect(w, r, fmt.Sprintf("/app/board/password/?redirect=%v", session), http.StatusTemporaryRedirect)
- return
- }
-
- if len(mapListBoard) == 0 {
- http.Redirect(w, r, "/app/dashboard/", http.StatusTemporaryRedirect)
- return
- }
- rows.Close()
- tabQuery := fmt.Sprintf(`SELECT tab.id, tab.title, tab.board FROM tab JOIN boards ON boards.id=tab.board WHERE tab.board=%v;`, mapListBoard[0]["id"])
- rows, err = database.Query(tabQuery)
- if err != nil {
- log.Fatal(err)
- }
- cols, _ = rows.Columns()
- var mapListTabs []map[string]interface{}
- for rows.Next() {
- // Create a slice of interface{}'s to represent each column,
- // and a second slice to contain pointers to each item in the columns slice.
- columns := make([]interface{}, len(cols))
- columnPointers := make([]interface{}, len(cols))
- for i, _ := range columns {
- columnPointers[i] = &columns[i]
- }
-
- // Scan the result into the column pointers...
- if err := rows.Scan(columnPointers...); err != nil {
-
- }
-
- // Create our map, and retrieve the value for each column from the pointers slice,
- // storing it in the map with the name of the column as the key.
- m := make(map[string]interface{})
- for i, colName := range cols {
- val := columnPointers[i].(*interface{})
- m[colName] = *val
- }
-
- // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
- //fmt.Println(m)
- mapListTabs = append(mapListTabs, m)
- }
- //currentTab := mapListTabs[0]["id"]
- // rows, err = database.Query(fmt.Sprintf("SELECT task.id, task.body, task.originalquestion, authentication_users.displayname, task.file FROM task JOIN boards ON boards.session=task.board JOIN authentication_users ON task.owner=authentication_users.id WHERE active=true AND isPublic=true AND boards.session='%v' AND tab=%v ORDER BY task.timestamp desc;", session, currentTab))
- // if err != nil {
- // log.Fatal(err)
- // }
- // cols, _ = rows.Columns()
- // var mapList []map[string]interface{}
- // for rows.Next() {
- // // Create a slice of interface{}'s to represent each column,
- // // and a second slice to contain pointers to each item in the columns slice.
- // columns := make([]interface{}, len(cols))
- // columnPointers := make([]interface{}, len(cols))
- // for i, _ := range columns {
- // columnPointers[i] = &columns[i]
- // }
-
- // // Scan the result into the column pointers...
- // if err := rows.Scan(columnPointers...); err != nil {
-
- // }
-
- // // Create our map, and retrieve the value for each column from the pointers slice,
- // // storing it in the map with the name of the column as the key.
- // m := make(map[string]interface{})
- // for i, colName := range cols {
- // val := columnPointers[i].(*interface{})
- // m[colName] = *val
- // }
-
- // // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
- // //fmt.Println(m)
-
- // queryStr := fmt.Sprintf(`SELECT authentication_users.displayname FROM task JOIN task AS task_2 ON task_2.id=task.originalquestion FULL OUTER JOIN authentication_users ON authentication_users.id = task.owner WHERE task.complete = true AND (task.originalquestion=%v OR task_2.id=%v);`, m["originalquestion"], m["id"])
-
- // log.Println(fmt.Sprintf("\n===================\n%v\n===================\n", m["originalquestion"] ))
-
- // if (m["originalquestion"] == nil) {
- // queryStr = fmt.Sprintf(`SELECT authentication_users.displayname FROM task JOIN task AS task_2 ON task_2.id=task.originalquestion FULL OUTER JOIN authentication_users ON authentication_users.id = task.owner WHERE task.complete = true AND (task_2.id=%v);`, m["id"])
- // }
- // completed_rows, err := database.Query(queryStr)
- // if err != nil {
- // log.Fatal(err)
- // }
- // mapOfCompleted := getColumnMap(completed_rows)
- // m["completed"] = mapOfCompleted
- // m["body"] = template.HTML(m["body"].(string))
- // mapList = append(mapList, m)
- // }
- // rows.Close()
- // rows, err = database.Query(fmt.Sprintf("SELECT task.id, task.name, task.body, task.originalquestion, authentication_users.displayname, task.file FROM task JOIN boards ON boards.session=task.board JOIN authentication_users ON task.owner=authentication_users.id WHERE active=true AND isPublic=false AND complete=false AND boards.session='%v' AND task.owner=%v AND tab=%v ORDER BY task.timestamp desc;", session, userId, currentTab))
- // if err != nil {
- // log.Fatal(err)
- // }
- // defer rows.Close()
- // cols, _ = rows.Columns()
- // var mapListPrivate []map[string]interface{}
- // for rows.Next() {
- // // Create a slice of interface{}'s to represent each column,
- // // and a second slice to contain pointers to each item in the columns slice.
- // columns := make([]interface{}, len(cols))
- // columnPointers := make([]interface{}, len(cols))
- // for i, _ := range columns {
- // columnPointers[i] = &columns[i]
- // }
-
- // // Scan the result into the column pointers...
- // if err := rows.Scan(columnPointers...); err != nil {
-
- // }
-
- // // Create our map, and retrieve the value for each column from the pointers slice,
- // // storing it in the map with the name of the column as the key.
- // m := make(map[string]interface{})
- // for i, colName := range cols {
- // val := columnPointers[i].(*interface{})
- // m[colName] = *val
- // }
- // queryStr := fmt.Sprintf(`SELECT authentication_users.displayname FROM task JOIN task AS task_2 ON task_2.id=task.originalquestion FULL OUTER JOIN authentication_users ON authentication_users.id = task.owner WHERE task.complete = true AND (task.originalquestion=%v OR task_2.id=%v);`, m["originalquestion"], m["id"])
- // if (m["originalquestion"] == nil) {
- // queryStr = fmt.Sprintf(`SELECT authentication_users.displayname FROM task JOIN task AS task_2 ON task_2.id=task.originalquestion FULL OUTER JOIN authentication_users ON authentication_users.id = task.owner WHERE task.complete = true AND (task_2.id=%v);`, m["id"])
- // }
- // completed_rows, err := database.Query(queryStr)
- // if err != nil {
- // log.Fatal(err)
- // }
- // mapOfCompleted := getColumnMap(completed_rows)
- // m["completed"] = mapOfCompleted
- // m["body"] = template.HTML(m["body"].(string))
- // // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
- // //fmt.Println(m)
- // mapListPrivate = append(mapListPrivate, m)
- // }
- // rows.Close()
- // rows, err = database.Query(fmt.Sprintf("SELECT task.id, task.name, task.body, task.originalquestion, authentication_users.displayname, task.file FROM task JOIN authentication_users ON task.owner=authentication_users.id JOIN boards ON boards.session=task.board WHERE active=true AND isPublic=false AND complete=true AND boards.session='%v' AND task.owner=%v AND tab=%v ORDER BY task.timestamp desc;", session, userId, currentTab))
- // if err != nil {
- // log.Fatal(err)
- // }
- // cols, _ = rows.Columns()
- // var mapListComplete []map[string]interface{}
- // for rows.Next() {
- // // Create a slice of interface{}'s to represent each column,
- // // and a second slice to contain pointers to each item in the columns slice.
- // columns := make([]interface{}, len(cols))
- // columnPointers := make([]interface{}, len(cols))
- // for i, _ := range columns {
- // columnPointers[i] = &columns[i]
- // }
-
- // // Scan the result into the column pointers...
- // if err := rows.Scan(columnPointers...); err != nil {
-
- // }
-
- // // Create our map, and retrieve the value for each column from the pointers slice,
- // // storing it in the map with the name of the column as the key.
- // m := make(map[string]interface{})
- // for i, colName := range cols {
- // val := columnPointers[i].(*interface{})
- // m[colName] = *val
- // }
- // queryStr := fmt.Sprintf(`SELECT authentication_users.displayname FROM task JOIN task AS task_2 ON task_2.id=task.originalquestion FULL OUTER JOIN authentication_users ON authentication_users.id = task.owner WHERE task.complete = true AND (task.originalquestion=%v OR task_2.id=%v);`, m["originalquestion"], m["id"])
- // if (m["originalquestion"] == nil) {
- // queryStr = fmt.Sprintf(`SELECT authentication_users.displayname FROM task JOIN task AS task_2 ON task_2.id=task.originalquestion FULL OUTER JOIN authentication_users ON authentication_users.id = task.owner WHERE task.complete = true AND (task_2.id=%v);`, m["id"])
- // }
- // completed_rows, err := database.Query(queryStr)
- // if err != nil {
- // log.Fatal(err)
- // }
- // mapOfCompleted := getColumnMap(completed_rows)
- // m["completed"] = mapOfCompleted
- // m["body"] = template.HTML(m["body"].(string))
- // // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
- // //fmt.Println(m)
- // mapListComplete = append(mapListComplete, m)
- // }
- // rows.Close()
- taskForm := forms.BaseForm(forms.POST, "").SetId("taskForm").SetParam("name", "taskForm").Elements(
- fields.TextAreaField("Body", 30, 50).AddClass("materialize-textarea").SetLabel("Body"),
- fields.SubmitButton("submit", "Submit").AddClass("waves-effect waves-light btn"),
- )
- log.Println(mapListTabs[0]["id"])
- var firstTab int64
- cookie, err := r.Cookie("lastTab")
- if err == nil {
- cookieVal, err := strconv.Atoi(cookie.Value)
- if err != nil{
-
- }
- firstTab = int64(cookieVal)
- }else{
- firstTab = mapListTabs[0]["id"].(int64)
- }
- log.Println(firstTab)
-
- userIdInt, err := strconv.Atoi(userId)
- //"publicTasks": mapList, "privateTasks": mapListPrivate, "completeTasks": mapListComplete
- renderTemplate(w, "board_index_redux.html", map[string]interface{}{"UserId": userIdInt, "FirstTab": firstTab, "Tabs": mapListTabs, "Board":mapListBoard[0], "SessionId": session, "taskForm": taskForm}, r)
- })
- r.HandleFunc("/app/courses/create/", func(w http.ResponseWriter, r *http.Request) {
- currentUser := getUserName(r)
- if currentUser == "" {
- http.Redirect(w, r, "/register/login/?redirect=/app/courses/create/", http.StatusTemporaryRedirect)
- return
- }
- form := forms.BaseFormFromModel(adminModels["course"], forms.POST, "/api/courses/create/").SetParam("name", "courseForm")
- taskForm := forms.BaseFormFromModel(adminModels["task"], forms.POST, "").SetId("taskForm").SetParam("name", "taskForm")
- renderTemplate(w, "courses_create_new.html", map[string]interface{}{"form": form, "taskForm": taskForm}, r)
- })
-
- r.HandleFunc("/admin/{model}/", func(w http.ResponseWriter, r *http.Request) {
- vars := mux.Vars(r)
- form := forms.BaseFormFromModel(adminModels[vars["model"]], forms.POST, "")
- renderTemplate(w, "admin_model.html", map[string]interface{}{"form": form}, r)
- })
- r.HandleFunc("/admin/{model}/add/", func(w http.ResponseWriter, r *http.Request) {
- vars := mux.Vars(r)
- form := forms.BaseFormFromModel(adminModels[vars["model"]], forms.POST, "")
- renderTemplate(w, "admin_create_model.html", map[string]interface{}{"form": form, "model": vars["model"]}, r)
- })
-
- r.HandleFunc("/admin/{model}/{id:[0-9]+}/", func(w http.ResponseWriter, r *http.Request) {
- //TODO Make this interface work on dynamic typing
- vars := mux.Vars(r)
- var objectDoesNotExist = false
- var currentModel Course
- query := fmt.Sprintf("SELECT * FROM %v WHERE %v.id='%v';", vars["model"], vars["model"], vars["id"])
- rows, err := db.MainDatabase.Query(query)
- if err != nil {
- log.Fatal(err)
- }
- n, err := dbr.Load(rows, ¤tModel)
- if err != nil {
- log.Fatal(err)
- }
- if n != 1 {
- objectDoesNotExist = true
- }
- form := forms.BaseFormFromModel(currentModel, forms.POST, "")
- data := map[string]interface{}{"form": form, "model": vars["model"]}
- if objectDoesNotExist {
- data["form"] = nil
- }
- renderTemplate(w, "admin_create_model.html", data, r)
- })
- r.HandleFunc("/api/register/signup/", func(w http.ResponseWriter, r *http.Request) {
- firstName := r.FormValue("first_name")
- //lastName := r.FormValue("last_name")
- email := r.FormValue("email")
- password := r.FormValue("password")
- confirmPassword := r.FormValue("password_confirm")
- confirmTerms := r.FormValue("agree_terms")
- captcha := r.FormValue("g-recaptcha-response")
-
- confirmCaptcha, error := recaptcha.Confirm (getIPAdress(r), captcha)
- if error != nil {
- log.Println(error)
- }
- if confirmTerms != "true" {
- fmt.Fprintf(w, "{\"Error\":\"Please agree to the Terms of Use and Privacy Policy.\"}")
- return
- }
- if !confirmCaptcha {
- fmt.Fprintf(w, "{\"Error\":\"Please fill out captcha.\"}")
- return
- }
- if password != confirmPassword {
- log.Println("Passwords do not match.")
- fmt.Fprintf(w, "{\"Error\":\"Your password must match.\"}")
- return
- }
- err := checkmail.ValidateFormat(email)
- if err != nil {
- fmt.Println(err)
- fmt.Fprintf(w, "{\"Error\":\"Please enter a valid email address (example@example.com).\"}")
- return
- }
- didCreate, id := auth.CreateUser(email, "maxmarksjr", password, firstName, "foo.db")
- if !didCreate {
- fmt.Fprintf(w, "{\"Error\":\"Account Exists\"}")
- return
- }
- setSession(email,id, w)
- fmt.Fprintf(w, "{\"Success\":\"Account Created\"}")
- })
- r.HandleFunc("/api/register/login/", func(w http.ResponseWriter, r *http.Request) {
- email := r.FormValue("email")
- password := r.FormValue("password")
- didLogin, id := auth.LoginUser(email, password)
- if didLogin {
- setSession(email, id, w)
- fmt.Println("User Logged in")
- fmt.Fprintf(w, "{\"Success\":\"User Logged In\"}")
- } else {
- clearSession(w)
- fmt.Println("User not logged in")
- fmt.Fprintf(w, "{\"Error\":\"Incorrect\"}")
- }
- })
- r.HandleFunc("/api/tasks/delete/", func(w http.ResponseWriter, r *http.Request) {
- currentUser := getUserName(r)
- if currentUser == "" {
- fmt.Fprintf(w, `{"Error":"Not Authenticated"}`)
- return
- }
- userId := getUserId(r)
- task := r.FormValue("task")
- database := db.MainDatabase
- insert_row, error := database.Query(fmt.Sprintf("UPDATE task SET active=false WHERE owner=%v AND id=%v;", userId, task))
- if error != nil {
- log.Println(error)
- fmt.Fprintf(w, `{"Error":"Not Task Owner"}`)
- return
- }
-
- for insert_row.Next() {
- continue
- }
- fmt.Fprintf(w, "{\"Success\":\"User Logged In\"}")
- })
-
- r.HandleFunc("/api/tasks/file/", func(w http.ResponseWriter, r *http.Request) {
- log.Println("File Upload Started...")
- currentUser := getUserName(r)
- if currentUser == "" {
- fmt.Fprintf(w, `{"Error":"Not Authenticated"}`)
- return
- }
- userId := getUserId(r)
- file, handler, err := r.FormFile("fileUploadPrivate")
- if err != nil {
- log.Println(err)
- }
- defer file.Close()
- f, err := os.OpenFile(fmt.Sprintf("temp/%v", handler.Filename), os.O_WRONLY|os.O_CREATE, 0666)
- if err != nil {
- log.Fatal(err)
- }
- fmt.Println(f.Name()) // For example "dir/prefix054003078"
- io.Copy(f, file)
- //TODO Write the code to get the file
- contentType := mime.TypeByExtension(filepath.Ext(f.Name()))
- // Upload the file with FPutObject
- n, err := minioClient.FPutObject(bucketName, fmt.Sprintf("media/%v/%v", userId, handler.Filename), f.Name(), minio.PutObjectOptions{ContentType:contentType})
- if err != nil {
- log.Fatalln(err)
- }
- log.Printf("Successfully uploaded %s of size %d\n", handler.Filename, n)
- os.Remove(f.Name())
- log.Println(file)
-
- var tmpMsg Message
- tmpMsg.File = fmt.Sprintf("/media/%v/", userId)+handler.Filename
- //tmpMsg.Id = r.FormValue("signature")
- log.Println("File Uploading")
- log.Println(r.FormValue("signature"))
- tmpMsg.Signature = r.FormValue("signature")
- tmpMsg.Session = r.FormValue("session")
- tmpMsg.Message = r.FormValue("Message")
- tmpMsg.IsPublic = false
- tmpMsg.Tab, err = strconv.Atoi(r.FormValue("tab"))
- tmpMsg.Creating = true
- tmpMsg.Id = -1
- database := db.MainDatabase
- insert_row, error := database.Query(fmt.Sprintf("INSERT INTO task(name, body, isPublic, board, owner, tab, file) VALUES ('%v', '%v', %v, '%v', %v, %v, '%v') RETURNING id;", currentUser, tmpMsg.Message, tmpMsg.IsPublic, tmpMsg.Session, userId, tmpMsg.Tab, tmpMsg.File))
- if error != nil {
- log.Fatal(error)
- }
- var id int
- for insert_row.Next() {
- err := insert_row.Scan(&id)
- if err != nil {
- log.Fatal(err)
- }
- }
- rows, err := database.Query(fmt.Sprintf("SELECT task.id, task.owner, task.body, task.originalquestion, authentication_users.displayname, task.file FROM task JOIN boards ON boards.session=task.board JOIN authentication_users ON task.owner=authentication_users.id WHERE task.id=%v;", id))
- if err != nil {
- log.Fatal(err)
- }
- tmpMsg.Task = getColumnMap(rows)[0]
- tmpMsg.Id = id
- // Send it out to every client that is currently connected
- for client := range clients {
- if tmpMsg.Session == clientId[client]{
- err := client.WriteJSON(tmpMsg)
- if err != nil {
- log.Printf("error: %v", err)
- client.Close()
- delete(clients, client)
- }
- }
- }
- fmt.Fprintf(w, "{\"Success\":\"User Logged In\"}")
- })
- r.HandleFunc("/api/tasks/file/public/", func(w http.ResponseWriter, r *http.Request) {
- currentUser := getUserName(r)
- if currentUser == "" {
- fmt.Fprintf(w, `{"Error":"Not Authenticated"}`)
- return
- }
- userId := getUserId(r)
- file, handler, err := r.FormFile("fileUploadPublic")
- if err != nil {
- log.Println(err)
- }
- defer file.Close()
- f, err := os.OpenFile(fmt.Sprintf("temp/%v", handler.Filename), os.O_WRONLY|os.O_CREATE, 0666)
- if err != nil {
- log.Fatal(err)
- }
- fmt.Println(f.Name()) // For example "dir/prefix054003078"
- io.Copy(f, file)
- //TODO Write the code to get the file
- contentType := "application/octet-stream"
- // Upload the file with FPutObject
- n, err := minioClient.FPutObject(bucketName, fmt.Sprintf("media/%v/%v", userId, handler.Filename), f.Name(), minio.PutObjectOptions{ContentType:contentType})
- if err != nil {
- log.Fatalln(err)
- }
- log.Printf("Successfully uploaded %s of size %d\n", handler.Filename, n)
- os.Remove(f.Name())
- log.Println(file)
- // os.Mkdir(fmt.Sprintf("../public/static/media/%v/", userId), 0777)
- // f, err := os.OpenFile(fmt.Sprintf("../public/static/media/%v/", userId) + handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
- // defer f.Close()
- // io.Copy(f, file)
-
- // log.Println(file)
- //currentSession := r.FormValue("session")
-
- var tmpMsg Message
- tmpMsg.File = fmt.Sprintf("/media/%v/", userId)+handler.Filename
- //tmpMsg.Id = r.FormValue("signature")
- log.Println("File Uploading")
- log.Println(r.FormValue("signature"))
- tmpMsg.Signature = r.FormValue("signature")
- tmpMsg.Session = r.FormValue("session")
- tmpMsg.Message = r.FormValue("Message")
- tmpMsg.IsPublic = true
- tmpMsg.Tab, err = strconv.Atoi(r.FormValue("tab"))
- tmpMsg.Creating = true
- tmpMsg.Id = -1
- database := db.MainDatabase
- insert_row, error := database.Query(fmt.Sprintf("INSERT INTO task(name, body, isPublic, board, owner, tab, file) VALUES ('%v', '%v', %v, '%v', %v, %v, '%v') RETURNING id;", currentUser, tmpMsg.Message, tmpMsg.IsPublic, tmpMsg.Session, userId, tmpMsg.Tab, tmpMsg.File))
- if error != nil {
- log.Fatal(error)
- }
- var id int
- for insert_row.Next() {
- err := insert_row.Scan(&id)
- if err != nil {
- log.Fatal(err)
- }
- }
- rows, err := database.Query(fmt.Sprintf("SELECT task.id, task.owner, task.body, task.originalquestion, authentication_users.displayname, task.file FROM task JOIN boards ON boards.session=task.board JOIN authentication_users ON task.owner=authentication_users.id WHERE task.id=%v;", id))
- if err != nil {
- log.Fatal(err)
- }
- tmpMsg.Task = getColumnMap(rows)[0]
- tmpMsg.Id = id
- // Send it out to every client that is currently connected
- for client := range clients {
- if tmpMsg.Session == clientId[client]{
- err := client.WriteJSON(tmpMsg)
- if err != nil {
- log.Printf("error: %v", err)
- client.Close()
- delete(clients, client)
- }
- }
- }
- fmt.Fprintf(w, "{\"Success\":\"User Logged In\"}")
- })
- r.HandleFunc("/api/courses/create/", func(w http.ResponseWriter, r *http.Request) {
- currentUser := getUserName(r)
- if currentUser == "" {
- fmt.Fprintf(w, `{"Error":"Not Authenticated"}`)
- return
- }
- name := r.FormValue("Name")
- description := r.FormValue("Description")
- courseType := r.FormValue("Type")
- catagory := r.FormValue("Catagory")
- isPublic := r.FormValue("IsPublic")
- database := db.MainDatabase
- insert_row, error := database.Query(fmt.Sprintf("INSERT INTO course(name, description, type, catagory, isPublic) VALUES ('%v', '%v', '%v', '%v', '%v');", name, description, courseType, catagory, isPublic))
- if error != nil {
- log.Println(error)
- fmt.Fprintf(w, "{\"Error\":\"Server Error\"}")
- return
- }
- for insert_row.Next() {
- continue
- }
- fmt.Fprintf(w, "{\"Success\":\"Course Created\"}")
- })
- r.HandleFunc("/api/boards/add/", func(w http.ResponseWriter, r *http.Request) {
- userId := getUserId(r)
- if userId == "" {
- return
- }
- boardId := r.FormValue("boardId")
- database := db.MainDatabase
- insertQuery := fmt.Sprintf("INSERT INTO user_boards VALUES (%v, %v);", userId, boardId)
- log.Println(insertQuery)
- insert_row, error := database.Query(insertQuery)
- if error != nil {
- log.Println(error)
- fmt.Fprintf(w, "{\"Error\":\"Server Error\"}")
- return
- }
- for insert_row.Next() {
- continue
- }
- fmt.Fprintf(w, "{\"Success\":\"Board Added\"}")
- })
- r.HandleFunc("/api/survey/intro/", func(w http.ResponseWriter, r *http.Request) {
- currentSurveySession := getSurveySession(r)
- fmt.Printf("\nHello World My Name is %v\n", currentSurveySession)
- questionId := r.FormValue("question")
- question := survey.Get_Survey_Question(questionId)
- if questionId == "4" {
- if err := r.ParseForm(); err != nil {
- // handle error
- }
- fmt.Println(r.PostForm["mainInput"])
- response := survey.Process_Task_Answer(r.PostForm["mainInput"], question, questionId, currentSurveySession)
- if response != "" {
- fmt.Fprintf(w, response)
- } else {
- fmt.Fprintf(w, "{\"Error\":\"Incorrect\"}")
- }
- }else if questionId == "5"{
- //name := results["name"][0]
- //Check if the user is logged in
- survey.SessionList[currentSurveySession]["mainInput"] = r.PostForm["mainInput"]
- survey.SessionList[currentSurveySession]["password"] = r.PostForm["password"]
- currentUser := getUserName(r)
- if currentUser == "" {
- fmt.Fprintf(w, "{\"Error\":\"No Auth\"}")
- return
- }
- userId := getUserId(r)
- results := survey.SessionList[currentSurveySession]
- vision := sanitizeInput(results["vision"][0])
- tasks := results["tasks"]
- boardName := sanitizeInput(r.PostForm["mainInput"][0])
- password := sanitizeInput(r.PostForm["password"][0])
- projectType := sanitizeInput(results["type"][0])
- sessionId := xid.New()
- insertQuery := fmt.Sprintf("INSERT INTO boards (name, vision, session, password, type, owner) VALUES ('%v', '%v', '%v', '%v', '%v', %v) RETURNING id;", boardName, vision, sessionId, password, projectType, userId)
- database := db.MainDatabase
- insert_row, error := database.Query(insertQuery)
- var boardId int
- if error != nil {
- log.Println(error)
- fmt.Fprintf(w, "{\"Error\":\"Server Error\"}")
- return
- }
- for insert_row.Next() {
- err := insert_row.Scan(&boardId)
- if err != nil {
- log.Fatal(err)
- }
- }
- insertQuery = fmt.Sprintf("INSERT INTO user_boards (auth_user, boards) VALUES (%v, %v);", userId, boardId)
- log.Println(insertQuery)
- insert_row, error = database.Query(insertQuery)
- if error != nil {
- log.Println(error)
- fmt.Fprintf(w, "{\"Error\":\"Server Error\"}")
- return
- }
- for insert_row.Next() {
- continue
- }
- insertQuery = fmt.Sprintf("INSERT INTO tab (title, board) VALUES ('Main', %v) RETURNING id;", boardId)
- log.Println(insertQuery)
- insert_row, error = database.Query(insertQuery)
-
- var tabId int
- if error != nil {
- log.Println(error)
- fmt.Fprintf(w, "{\"Error\":\"Server Error\"}")
- return
- }
- for insert_row.Next() {
- err := insert_row.Scan(&tabId)
- if err != nil {
- log.Fatal(err)
- }
- }
- insertQuery = "INSERT INTO task (body, board, owner, isPublic, complete, tab) VALUES %v;"
- var buffer bytes.Buffer
- for index := range tasks {
- currentStr := fmt.Sprintf(`('%v', '%v', %v, false, true, %v)`, sanitizeInput(tasks[index]), sessionId, userId, tabId)
- buffer.WriteString(currentStr)
- if index != len(tasks) - 1 {
- buffer.WriteString(",")
- }
- }
- insertQuery = fmt.Sprintf(insertQuery, buffer.String())
- fmt.Println(insertQuery)
- insert_row, error = database.Query(insertQuery)
- if error != nil {
- log.Println(error)
- }
- for insert_row.Next() {
- continue
- }
-
- fmt.Fprintf(w, "{\"Done\":\"Complete\"}")
- return
- }else{
- answer := r.FormValue("mainInput")
- fmt.Println(answer)
- fmt.Printf(questionId)
- response := survey.Process_Intro_Answer(answer, question, questionId, currentSurveySession)
- fmt.Println(response)
- fmt.Println("========================")
- //fmt.Println(question[0])
- //fmt.Println(response)
- if response != "" {
- fmt.Fprintf(w, response)
- } else {
- fmt.Fprintf(w, "{\"Error\":\"Incorrect\"}")
- }
- }
-
- //fmt.Fprintf(w, "{\"Error\":\"Incorrect\"}")
- })
- r.HandleFunc("/app/board/finish/", func(w http.ResponseWriter, r *http.Request) {
- currentSurveySession := getSurveySession(r)
- //Check if the user is logged in
- currentUser := getUserName(r)
- if currentUser == "" {
- fmt.Fprintf(w, "{\"Error\":\"No Auth\"}")
- return
- }
- results := survey.SessionList[currentSurveySession]
- userId := getUserId(r)
- fmt.Printf("\n\n%v\n\n", results)
- vision := sanitizeInput(results["vision"][0])
- tasks := results["tasks"]
- boardName := sanitizeInput(results["mainInput"][0])
- password := sanitizeInput(results["password"][0])
- projectType := sanitizeInput(results["type"][0])
- sessionId := xid.New()
- insertQuery := fmt.Sprintf("INSERT INTO boards (name, vision, session, password, type, owner) VALUES ('%v', '%v', '%v', '%v', '%v', %v) RETURNING id;", boardName, vision, sessionId, password, projectType, userId)
- log.Println(insertQuery)
- database := db.MainDatabase
- insert_row, error := database.Query(insertQuery)
- var boardId int
- if error != nil {
- log.Println(error)
- fmt.Fprintf(w, "{\"Error\":\"Server Error\"}")
- return
- }
- for insert_row.Next() {
- err := insert_row.Scan(&boardId)
- if err != nil {
- log.Fatal(err)
- }
- }
- insertQuery = fmt.Sprintf("INSERT INTO user_boards VALUES (%v, %v);", userId, boardId)
- log.Println(insertQuery)
- insert_row, error = database.Query(insertQuery)
- if error != nil {
- log.Println(error)
- fmt.Fprintf(w, "{\"Error\":\"Server Error\"}")
- return
- }
- for insert_row.Next() {
- continue
- }
- insertQuery = fmt.Sprintf("INSERT INTO tab (title, board) VALUES ('Main', %v) RETURNING id;", boardId)
- log.Println(insertQuery)
- insert_row, error = database.Query(insertQuery)
-
- var tabId int
- if error != nil {
- log.Println(error)
- fmt.Fprintf(w, "{\"Error\":\"Server Error\"}")
- return
- }
- for insert_row.Next() {
- err := insert_row.Scan(&tabId)
- if err != nil {
- log.Fatal(err)
- }
- }
- insertQuery = "INSERT INTO task (body, board, owner, isPublic, complete, tab) VALUES %v;"
- var buffer bytes.Buffer
- for index := range tasks {
- currentStr := fmt.Sprintf(`('%v', '%v', %v, false, true, %v)`, sanitizeInput(tasks[index]), sessionId, userId, tabId)
- buffer.WriteString(currentStr)
- if index != len(tasks) - 1 {
- buffer.WriteString(",")
- }
- }
- insertQuery = fmt.Sprintf(insertQuery, buffer.String())
- fmt.Println(insertQuery)
- insert_row, error = database.Query(insertQuery)
- if error != nil {
- log.Println(error)
- }
- for insert_row.Next() {
- continue
- }
-
- http.Redirect(w, r, fmt.Sprintf("/app/boards/%v/",sessionId), http.StatusTemporaryRedirect)
- return
- })
- r.HandleFunc("/app/dashboard/", func(w http.ResponseWriter, r *http.Request) {
- currentUser := getUserName(r)
- if currentUser == "" {
- http.Redirect(w, r, "/register/login/?redirect=/app/dashboard/", http.StatusTemporaryRedirect)
- return
- }
- …
Large files files are truncated, but you can click here to view the full file