PageRenderTime 808ms CodeModel.GetById 43ms RepoModel.GetById 1ms app.codeStats 1ms

/src/main.go

https://bitbucket.org/maxmarksjr/fluxbackend
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

  1. package main
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "fmt"
  6. "html/template"
  7. "log"
  8. // "flag"
  9. "net/http"
  10. "os"
  11. // "net/url"
  12. "path/filepath"
  13. "regexp"
  14. "strings"
  15. "bytes"
  16. "database/sql"
  17. "strconv"
  18. "io"
  19. "net"
  20. "mime"
  21. "io/ioutil"
  22. // "math/rand"
  23. // "reflect"
  24. auth "./authentication"
  25. db "./local_database"
  26. survey "./survey"
  27. "github.com/minio/minio-go"
  28. "github.com/badoux/checkmail"
  29. "github.com/fsnotify/fsnotify"
  30. "github.com/gorilla/mux"
  31. "github.com/gorilla/securecookie"
  32. "github.com/gorilla/websocket"
  33. "github.com/oxtoacart/bpool"
  34. uuid "github.com/satori/go.uuid"
  35. "gopkg.in/mgo.v2/bson"
  36. "github.com/rs/xid"
  37. "github.com/dpapathanasiou/go-recaptcha"
  38. "github.com/kirves/go-form-it" // import directly into this repo
  39. "github.com/kirves/go-form-it/fields"
  40. "github.com/gocraft/dbr"
  41. )
  42. var clients = make(map[*websocket.Conn]bool)
  43. var clientId = make(map[*websocket.Conn]string)
  44. var clientUser = make(map[*websocket.Conn]string)
  45. var broadcast = make(chan Message)
  46. // var socketClients = make(map[string], map[*websocket.Conn]bool)
  47. var upgrader = websocket.Upgrader{}
  48. var Global = 0 // For testing rooms functionality
  49. type Message struct {
  50. Id int `json:"id"`
  51. Email string `json:"email"`
  52. Username string `json:"username"`
  53. Message string `json:"message"`
  54. IsPublic bool `json:"isPublic"`
  55. Signature string `json:"signature"`
  56. Complete bool `json:"complete"`
  57. Creating bool `json:"creating"`
  58. Session string `json:"session"`
  59. OriginalQuestion int `json:"originalquestion"`
  60. IsTab bool `json:"isTab"`
  61. Tab int `json:"tab"`
  62. File string `json:"file"`
  63. Owner string `json:"owner"`
  64. Task map[string]interface{} `json:"task"`
  65. }
  66. type Answer struct {
  67. Question int `json:"question"`
  68. Response string `json:"response"`
  69. }
  70. type Course struct {
  71. Name string
  72. Description string `form_widget:"textarea"`
  73. Type string
  74. LessonsSections int `form_options:"skip"`
  75. TotalSections int `form_options:"skip"`
  76. Link string `form_options:"skip"`
  77. Difficulty int `form_options:"skip"`
  78. Catagory string
  79. IsPublic bool `form_label:"Is Public"`
  80. }
  81. type Task struct {
  82. Name string `json:"name"`
  83. Body string `json:"body"`
  84. IsPublic string `json:"isPublic"`
  85. OriginalQuestion int `json:"originalQuestion"`
  86. Complete bool `json:"complete"`
  87. Board string `json:"board"`
  88. Owner int `json:"owner"`
  89. Tab int `json:"tab"`
  90. Index int `json:"index"`
  91. }
  92. //Basic user Structure (translates into SQL model)
  93. type User struct {
  94. Email string `json:"email"`
  95. Username string `json:"username"`
  96. DisplayName string `json:"display_name"`
  97. }
  98. type PageTemplate struct {
  99. Main string
  100. }
  101. func main() {
  102. // Create simple fileserver
  103. r := mux.NewRouter()
  104. fs := http.FileServer(http.Dir("../public/static/"))
  105. loadTemplates()
  106. http.Handle("/", r)
  107. http.Handle("/static/", http.StripPrefix("/static/", fs))
  108. //Add log to file
  109. //https://stackoverflow.com/questions/19965795/go-golang-write-log-to-file
  110. // f, err := os.OpenFile("golog.log", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
  111. // if err != nil {
  112. // log.Fatalf("Error opening file: %v", err)
  113. // }
  114. // defer f.Close()
  115. // log.SetOutput(f)
  116. log.SetFlags(log.LstdFlags | log.Lshortfile)
  117. //Digital Ocean Spaces SDK
  118. endpoint := "s3.amazonaws.com"
  119. accessKeyID := "AKIAIWRI2VNGP4PCA2EA"
  120. secretAccessKey := "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"
  121. useSSL := true
  122. // Initialize minio client object.
  123. minioClient, err := minio.New(endpoint, accessKeyID, secretAccessKey, useSSL)
  124. if err != nil {
  125. log.Fatalln(err)
  126. }
  127. // Make a new bucket called mymusic.
  128. bucketName := "paariomain"
  129. location := "us-east-2"
  130. err = minioClient.MakeBucket(bucketName, location)
  131. if err != nil {
  132. // Check to see if we already own this bucket (which happens if you run this twice)
  133. exists, err := minioClient.BucketExists(bucketName)
  134. if err == nil && exists {
  135. log.Printf("We already own %s\n", bucketName)
  136. } else {
  137. log.Fatalln(err)
  138. }
  139. }
  140. log.Printf("Successfully created %s\n", bucketName)
  141. adminModels := map[string]interface{}{
  142. "course": Course{},
  143. "task": Task{},
  144. }
  145. recaptcha.Init ("6LfBNFwUAAAAANnttb-9nUX83ZZw4LrOTLKdAQiI")
  146. //survey.Load_Survey_Database()
  147. //For local testing
  148. db.Connect_To_Test_Database()
  149. survey.Load_Survey_Database()
  150. defer survey.MongoDatabase.Close()
  151. defer survey.QuestionDatabase.Close()
  152. defer db.MainDatabase.Close()
  153. r.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  154. renderTemplate(w, "404.html", nil, r)
  155. })
  156. r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  157. currentUser := getUserName(r)
  158. if currentUser != "" {
  159. http.Redirect(w, r, "/app/dashboard/", http.StatusTemporaryRedirect)
  160. return
  161. }
  162. renderTemplate(w, "index.html", nil, r)
  163. })
  164. r.HandleFunc("/firebase-messaging-sw.js", func(w http.ResponseWriter, r *http.Request) {
  165. w.Header().Set("Content-Type", "text/javascript; charset=utf-8")
  166. b, err := ioutil.ReadFile("firebase-messaging-sw.js") // just pass the file name
  167. if err != nil {
  168. fmt.Print(err)
  169. }
  170. fmt.Fprintf(w, string(b))
  171. })
  172. r.HandleFunc("/api/users/token/", func(w http.ResponseWriter, r *http.Request) {
  173. currentUser := getUserName(r)
  174. if currentUser == "" {
  175. fmt.Fprintf(w, `{"Error":"Not Authenticated"}`)
  176. return
  177. }
  178. userId := getUserId(r)
  179. token := r.FormValue("token")
  180. database := db.MainDatabase
  181. rows, err := database.Query(fmt.Sprintf("SELECT fb_token FROM device WHERE fb_token='%v';", token))
  182. if err != nil {
  183. log.Println(err)
  184. }
  185. defer rows.Close()
  186. var count = 0
  187. for rows.Next() {
  188. count += 1
  189. }
  190. if count > 0 {
  191. fmt.Fprintf(w, "{\"Error\":\"Already Added Token\"}")
  192. return
  193. }
  194. rows, err = database.Query(fmt.Sprintf("INSERT INTO device (auth_user, fb_token) VALUES (%v, '%v');", userId, token))
  195. if err != nil {
  196. log.Println(err)
  197. }
  198. defer rows.Close()
  199. for rows.Next() {
  200. continue
  201. }
  202. fmt.Fprintf(w, "{\"Success\":\"Added Token\"}")
  203. })
  204. r.HandleFunc("/register/signup/", func(w http.ResponseWriter, r *http.Request) {
  205. redirect := r.URL.Query().Get("redirect")
  206. renderTemplate(w, "sign_up.html", map[string]interface{}{
  207. "RedirectUrl": redirect,
  208. }, r)
  209. })
  210. r.HandleFunc("/admin/", func(w http.ResponseWriter, r *http.Request) {
  211. renderTemplate(w, "admin_home.html", nil, r)
  212. })
  213. r.HandleFunc("/terms/", func(w http.ResponseWriter, r *http.Request) {
  214. renderTemplate(w, "terms.html", nil, r)
  215. })
  216. r.HandleFunc("/privacy/", func(w http.ResponseWriter, r *http.Request) {
  217. renderTemplate(w, "privacy.html", nil, r)
  218. })
  219. r.HandleFunc("/about/", func(w http.ResponseWriter, r *http.Request) {
  220. renderTemplate(w, "about.html", nil, r)
  221. })
  222. r.HandleFunc("/contact/", func(w http.ResponseWriter, r *http.Request) {
  223. renderTemplate(w, "contact.html", nil, r)
  224. })
  225. r.HandleFunc("/api/board/edit/", func(w http.ResponseWriter, r *http.Request) {
  226. currentUser := getUserName(r)
  227. if currentUser == "" {
  228. fmt.Fprintf(w, `{"Error":"Not Authenticated"}`)
  229. return
  230. }
  231. userId := getUserId(r)
  232. name := r.FormValue("board_name")
  233. vision := r.FormValue("board_vision")
  234. boardId := r.FormValue("board_id")
  235. database := db.MainDatabase
  236. rows, err := database.Query(fmt.Sprintf("SELECT id FROM boards WHERE owner=%v AND id=%v;", userId, boardId))
  237. if err != nil {
  238. log.Println(err)
  239. }
  240. defer rows.Close()
  241. var count = 0
  242. for rows.Next() {
  243. count += 1
  244. }
  245. if count <= 0 {
  246. fmt.Fprintf(w, "{\"Error\":\"Not Board Owner\"}")
  247. return
  248. }
  249. insert_row, error := database.Query(fmt.Sprintf("UPDATE boards SET name='%v', vision='%v' WHERE id=%v;", name, vision, boardId))
  250. if error != nil {
  251. log.Fatal(error)
  252. }
  253. for insert_row.Next() {
  254. continue
  255. }
  256. fmt.Fprintf(w, "{\"Success\":\"Board changed\"}")
  257. })
  258. // r.HandleFunc("/app/", func(w http.ResponseWriter, r *http.Request) {
  259. // renderTemplate(w, "admin_home.html", nil, r)
  260. // })
  261. r.HandleFunc("/api/board/tabs/get/", func(w http.ResponseWriter, r *http.Request) {
  262. currentUser := getUserName(r)
  263. if currentUser == "" {
  264. fmt.Fprintf(w, `{"Error":"Not Authenticated"}`)
  265. return
  266. }
  267. userId := getUserId(r)
  268. tab := r.FormValue("tab")
  269. session := r.FormValue("board")
  270. database := db.MainDatabase
  271. 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))
  272. if err != nil {
  273. log.Fatal(err)
  274. }
  275. cols, _ := rows.Columns()
  276. var mapList []map[string]interface{}
  277. notLast := rows.Next()
  278. for notLast {
  279. // Create a slice of interface{}'s to represent each column,
  280. // and a second slice to contain pointers to each item in the columns slice.
  281. columns := make([]interface{}, len(cols))
  282. columnPointers := make([]interface{}, len(cols))
  283. for i, _ := range columns {
  284. columnPointers[i] = &columns[i]
  285. }
  286. // Scan the result into the column pointers...
  287. if err := rows.Scan(columnPointers...); err != nil {
  288. }
  289. // Create our map, and retrieve the value for each column from the pointers slice,
  290. // storing it in the map with the name of the column as the key.
  291. m := make(map[string]interface{})
  292. for i, colName := range cols {
  293. val := columnPointers[i].(*interface{})
  294. m[colName] = *val
  295. }
  296. notLast = rows.Next()
  297. // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
  298. //fmt.Println(m)
  299. 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"])
  300. if (m["originalquestion"] == nil) {
  301. 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"])
  302. }
  303. completed_rows, err := database.Query(queryStr)
  304. if err != nil {
  305. log.Fatal(err)
  306. }
  307. mapOfCompleted := getColumnMap(completed_rows)
  308. m["completed"] = mapOfCompleted
  309. // m["body"] = template.HTML(m["body"].(string))
  310. mapList = append(mapList, m)
  311. }
  312. jsonStr, err := json.Marshal(mapList)
  313. if err != nil {
  314. log.Fatal(err)
  315. }
  316. privateString := string(jsonStr)
  317. rows.Close()
  318. 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))
  319. if err != nil {
  320. log.Fatal(err)
  321. }
  322. cols, _ = rows.Columns()
  323. var mapListComplete []map[string]interface{}
  324. notLast = rows.Next()
  325. for notLast {
  326. // Create a slice of interface{}'s to represent each column,
  327. // and a second slice to contain pointers to each item in the columns slice.
  328. columns := make([]interface{}, len(cols))
  329. columnPointers := make([]interface{}, len(cols))
  330. for i, _ := range columns {
  331. columnPointers[i] = &columns[i]
  332. }
  333. // Scan the result into the column pointers...
  334. if err := rows.Scan(columnPointers...); err != nil {
  335. }
  336. // Create our map, and retrieve the value for each column from the pointers slice,
  337. // storing it in the map with the name of the column as the key.
  338. m := make(map[string]interface{})
  339. for i, colName := range cols {
  340. val := columnPointers[i].(*interface{})
  341. m[colName] = *val
  342. }
  343. notLast = rows.Next()
  344. // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
  345. //fmt.Println(m)
  346. 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"])
  347. if (m["originalquestion"] == nil) {
  348. 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"])
  349. }
  350. completed_rows, err := database.Query(queryStr)
  351. if err != nil {
  352. log.Fatal(err)
  353. }
  354. mapOfCompleted := getColumnMap(completed_rows)
  355. m["completed"] = mapOfCompleted
  356. // m["body"] = template.HTML(m["body"].(string))
  357. mapListComplete = append(mapListComplete, m)
  358. }
  359. jsonStr, err = json.Marshal(mapListComplete)
  360. if err != nil {
  361. log.Fatal(err)
  362. }
  363. completeString := string(jsonStr)
  364. rows.Close()
  365. 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))
  366. if err != nil {
  367. log.Fatal(err)
  368. }
  369. cols, _ = rows.Columns()
  370. var mapListPublic []map[string]interface{}
  371. notLast = rows.Next()
  372. for notLast {
  373. // Create a slice of interface{}'s to represent each column,
  374. // and a second slice to contain pointers to each item in the columns slice.
  375. columns := make([]interface{}, len(cols))
  376. columnPointers := make([]interface{}, len(cols))
  377. for i, _ := range columns {
  378. columnPointers[i] = &columns[i]
  379. }
  380. // Scan the result into the column pointers...
  381. if err := rows.Scan(columnPointers...); err != nil {
  382. }
  383. // Create our map, and retrieve the value for each column from the pointers slice,
  384. // storing it in the map with the name of the column as the key.
  385. m := make(map[string]interface{})
  386. for i, colName := range cols {
  387. val := columnPointers[i].(*interface{})
  388. m[colName] = *val
  389. }
  390. notLast = rows.Next()
  391. // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
  392. //fmt.Println(m)
  393. 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"])
  394. if (m["originalquestion"] == nil) {
  395. 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"])
  396. }
  397. completed_rows, err := database.Query(queryStr)
  398. if err != nil {
  399. log.Fatal(err)
  400. }
  401. mapOfCompleted := getColumnMap(completed_rows)
  402. m["completed"] = mapOfCompleted
  403. // m["body"] = template.HTML(m["body"].(string))
  404. mapListPublic = append(mapListPublic, m)
  405. }
  406. jsonStr, err = json.Marshal(mapListPublic)
  407. if err != nil {
  408. log.Fatal(err)
  409. }
  410. publicString := string(jsonStr)
  411. rows.Close()
  412. fmt.Fprintf(w, `{"Success": {"private": %v, "public": %v, "complete": %v}}`, privateString, publicString, completeString)
  413. })
  414. r.HandleFunc("/app/board/", func(w http.ResponseWriter, r *http.Request) {
  415. database := db.MainDatabase
  416. rows, err := database.Query("SELECT id, name, body FROM task WHERE isPublic=true ORDER BY task.timestamp desc;")
  417. if err != nil {
  418. log.Fatal(err)
  419. }
  420. cols, _ := rows.Columns()
  421. var mapList []map[string]interface{}
  422. for rows.Next() {
  423. // Create a slice of interface{}'s to represent each column,
  424. // and a second slice to contain pointers to each item in the columns slice.
  425. columns := make([]interface{}, len(cols))
  426. columnPointers := make([]interface{}, len(cols))
  427. for i, _ := range columns {
  428. columnPointers[i] = &columns[i]
  429. }
  430. // Scan the result into the column pointers...
  431. if err := rows.Scan(columnPointers...); err != nil {
  432. }
  433. // Create our map, and retrieve the value for each column from the pointers slice,
  434. // storing it in the map with the name of the column as the key.
  435. m := make(map[string]interface{})
  436. for i, colName := range cols {
  437. val := columnPointers[i].(*interface{})
  438. m[colName] = *val
  439. }
  440. // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
  441. //fmt.Println(m)
  442. mapList = append(mapList, m)
  443. }
  444. rows.Close()
  445. rows, err = database.Query("SELECT id, name, body, originalquestion FROM task WHERE isPublic=false AND complete=false ORDER BY task.timestamp desc;")
  446. if err != nil {
  447. log.Fatal(err)
  448. }
  449. defer rows.Close()
  450. cols, _ = rows.Columns()
  451. var mapListPrivate []map[string]interface{}
  452. for rows.Next() {
  453. // Create a slice of interface{}'s to represent each column,
  454. // and a second slice to contain pointers to each item in the columns slice.
  455. columns := make([]interface{}, len(cols))
  456. columnPointers := make([]interface{}, len(cols))
  457. for i, _ := range columns {
  458. columnPointers[i] = &columns[i]
  459. }
  460. // Scan the result into the column pointers...
  461. if err := rows.Scan(columnPointers...); err != nil {
  462. }
  463. // Create our map, and retrieve the value for each column from the pointers slice,
  464. // storing it in the map with the name of the column as the key.
  465. m := make(map[string]interface{})
  466. for i, colName := range cols {
  467. val := columnPointers[i].(*interface{})
  468. m[colName] = *val
  469. }
  470. // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
  471. //fmt.Println(m)
  472. mapListPrivate = append(mapListPrivate, m)
  473. }
  474. rows.Close()
  475. rows, err = database.Query("SELECT id, name, body, originalquestion FROM task WHERE isPublic=false AND complete=true ORDER BY task.timestamp desc;")
  476. if err != nil {
  477. log.Fatal(err)
  478. }
  479. defer rows.Close()
  480. cols, _ = rows.Columns()
  481. var mapListComplete []map[string]interface{}
  482. for rows.Next() {
  483. // Create a slice of interface{}'s to represent each column,
  484. // and a second slice to contain pointers to each item in the columns slice.
  485. columns := make([]interface{}, len(cols))
  486. columnPointers := make([]interface{}, len(cols))
  487. for i, _ := range columns {
  488. columnPointers[i] = &columns[i]
  489. }
  490. // Scan the result into the column pointers...
  491. if err := rows.Scan(columnPointers...); err != nil {
  492. }
  493. // Create our map, and retrieve the value for each column from the pointers slice,
  494. // storing it in the map with the name of the column as the key.
  495. m := make(map[string]interface{})
  496. for i, colName := range cols {
  497. val := columnPointers[i].(*interface{})
  498. m[colName] = *val
  499. }
  500. // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
  501. //fmt.Println(m)
  502. mapListComplete = append(mapListComplete, m)
  503. }
  504. taskForm := forms.BaseForm(forms.POST, "").SetId("taskForm").SetParam("name", "taskForm").Elements(
  505. fields.TextAreaField("Body", 30, 50).AddClass("materialize-textarea").SetLabel("Body"),
  506. fields.SubmitButton("submit", "Submit").AddClass("waves-effect waves-light btn"),
  507. )
  508. renderTemplate(w, "board_index.html", map[string]interface{}{"taskForm": taskForm, "publicTasks": mapList, "privateTasks": mapListPrivate, "completeTasks": mapListComplete}, r)
  509. })
  510. r.HandleFunc("/app/boards/{session}/", func(w http.ResponseWriter, r *http.Request) {
  511. vars := mux.Vars(r)
  512. session := vars["session"]
  513. currentUser := getUserName(r)
  514. if currentUser == "" {
  515. http.Redirect(w, r, fmt.Sprintf("/register/login/?redirect=/app/boards/%v/", session), http.StatusTemporaryRedirect)
  516. return
  517. }
  518. database := db.MainDatabase
  519. rows, err := database.Query(fmt.Sprintf("SELECT * FROM boards WHERE session='%v';", session))
  520. if err != nil {
  521. log.Println(err)
  522. }
  523. cols, _ := rows.Columns()
  524. var mapListBoard []map[string]interface{}
  525. for rows.Next() {
  526. // Create a slice of interface{}'s to represent each column,
  527. // and a second slice to contain pointers to each item in the columns slice.
  528. columns := make([]interface{}, len(cols))
  529. columnPointers := make([]interface{}, len(cols))
  530. for i, _ := range columns {
  531. columnPointers[i] = &columns[i]
  532. }
  533. // Scan the result into the column pointers...
  534. if err := rows.Scan(columnPointers...); err != nil {
  535. }
  536. // Create our map, and retrieve the value for each column from the pointers slice,
  537. // storing it in the map with the name of the column as the key.
  538. m := make(map[string]interface{})
  539. for i, colName := range cols {
  540. val := columnPointers[i].(*interface{})
  541. m[colName] = *val
  542. }
  543. // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
  544. //fmt.Println(m)
  545. mapListBoard = append(mapListBoard, m)
  546. }
  547. userId := getUserId(r)
  548. password := r.FormValue("password")
  549. 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))
  550. if err != nil {
  551. log.Println(err)
  552. }
  553. defer rows.Close()
  554. var count = 0
  555. for rows.Next() {
  556. count += 1
  557. }
  558. if count <= 0 {
  559. http.Redirect(w, r, fmt.Sprintf("/app/board/password/?redirect=%v", session), http.StatusTemporaryRedirect)
  560. return
  561. }
  562. if len(mapListBoard) == 0 {
  563. http.Redirect(w, r, "/app/dashboard/", http.StatusTemporaryRedirect)
  564. return
  565. }
  566. rows.Close()
  567. 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"])
  568. rows, err = database.Query(tabQuery)
  569. if err != nil {
  570. log.Fatal(err)
  571. }
  572. cols, _ = rows.Columns()
  573. var mapListTabs []map[string]interface{}
  574. for rows.Next() {
  575. // Create a slice of interface{}'s to represent each column,
  576. // and a second slice to contain pointers to each item in the columns slice.
  577. columns := make([]interface{}, len(cols))
  578. columnPointers := make([]interface{}, len(cols))
  579. for i, _ := range columns {
  580. columnPointers[i] = &columns[i]
  581. }
  582. // Scan the result into the column pointers...
  583. if err := rows.Scan(columnPointers...); err != nil {
  584. }
  585. // Create our map, and retrieve the value for each column from the pointers slice,
  586. // storing it in the map with the name of the column as the key.
  587. m := make(map[string]interface{})
  588. for i, colName := range cols {
  589. val := columnPointers[i].(*interface{})
  590. m[colName] = *val
  591. }
  592. // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
  593. //fmt.Println(m)
  594. mapListTabs = append(mapListTabs, m)
  595. }
  596. //currentTab := mapListTabs[0]["id"]
  597. // 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))
  598. // if err != nil {
  599. // log.Fatal(err)
  600. // }
  601. // cols, _ = rows.Columns()
  602. // var mapList []map[string]interface{}
  603. // for rows.Next() {
  604. // // Create a slice of interface{}'s to represent each column,
  605. // // and a second slice to contain pointers to each item in the columns slice.
  606. // columns := make([]interface{}, len(cols))
  607. // columnPointers := make([]interface{}, len(cols))
  608. // for i, _ := range columns {
  609. // columnPointers[i] = &columns[i]
  610. // }
  611. // // Scan the result into the column pointers...
  612. // if err := rows.Scan(columnPointers...); err != nil {
  613. // }
  614. // // Create our map, and retrieve the value for each column from the pointers slice,
  615. // // storing it in the map with the name of the column as the key.
  616. // m := make(map[string]interface{})
  617. // for i, colName := range cols {
  618. // val := columnPointers[i].(*interface{})
  619. // m[colName] = *val
  620. // }
  621. // // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
  622. // //fmt.Println(m)
  623. // 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"])
  624. // log.Println(fmt.Sprintf("\n===================\n%v\n===================\n", m["originalquestion"] ))
  625. // if (m["originalquestion"] == nil) {
  626. // 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"])
  627. // }
  628. // completed_rows, err := database.Query(queryStr)
  629. // if err != nil {
  630. // log.Fatal(err)
  631. // }
  632. // mapOfCompleted := getColumnMap(completed_rows)
  633. // m["completed"] = mapOfCompleted
  634. // m["body"] = template.HTML(m["body"].(string))
  635. // mapList = append(mapList, m)
  636. // }
  637. // rows.Close()
  638. // 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))
  639. // if err != nil {
  640. // log.Fatal(err)
  641. // }
  642. // defer rows.Close()
  643. // cols, _ = rows.Columns()
  644. // var mapListPrivate []map[string]interface{}
  645. // for rows.Next() {
  646. // // Create a slice of interface{}'s to represent each column,
  647. // // and a second slice to contain pointers to each item in the columns slice.
  648. // columns := make([]interface{}, len(cols))
  649. // columnPointers := make([]interface{}, len(cols))
  650. // for i, _ := range columns {
  651. // columnPointers[i] = &columns[i]
  652. // }
  653. // // Scan the result into the column pointers...
  654. // if err := rows.Scan(columnPointers...); err != nil {
  655. // }
  656. // // Create our map, and retrieve the value for each column from the pointers slice,
  657. // // storing it in the map with the name of the column as the key.
  658. // m := make(map[string]interface{})
  659. // for i, colName := range cols {
  660. // val := columnPointers[i].(*interface{})
  661. // m[colName] = *val
  662. // }
  663. // 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"])
  664. // if (m["originalquestion"] == nil) {
  665. // 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"])
  666. // }
  667. // completed_rows, err := database.Query(queryStr)
  668. // if err != nil {
  669. // log.Fatal(err)
  670. // }
  671. // mapOfCompleted := getColumnMap(completed_rows)
  672. // m["completed"] = mapOfCompleted
  673. // m["body"] = template.HTML(m["body"].(string))
  674. // // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
  675. // //fmt.Println(m)
  676. // mapListPrivate = append(mapListPrivate, m)
  677. // }
  678. // rows.Close()
  679. // 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))
  680. // if err != nil {
  681. // log.Fatal(err)
  682. // }
  683. // cols, _ = rows.Columns()
  684. // var mapListComplete []map[string]interface{}
  685. // for rows.Next() {
  686. // // Create a slice of interface{}'s to represent each column,
  687. // // and a second slice to contain pointers to each item in the columns slice.
  688. // columns := make([]interface{}, len(cols))
  689. // columnPointers := make([]interface{}, len(cols))
  690. // for i, _ := range columns {
  691. // columnPointers[i] = &columns[i]
  692. // }
  693. // // Scan the result into the column pointers...
  694. // if err := rows.Scan(columnPointers...); err != nil {
  695. // }
  696. // // Create our map, and retrieve the value for each column from the pointers slice,
  697. // // storing it in the map with the name of the column as the key.
  698. // m := make(map[string]interface{})
  699. // for i, colName := range cols {
  700. // val := columnPointers[i].(*interface{})
  701. // m[colName] = *val
  702. // }
  703. // 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"])
  704. // if (m["originalquestion"] == nil) {
  705. // 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"])
  706. // }
  707. // completed_rows, err := database.Query(queryStr)
  708. // if err != nil {
  709. // log.Fatal(err)
  710. // }
  711. // mapOfCompleted := getColumnMap(completed_rows)
  712. // m["completed"] = mapOfCompleted
  713. // m["body"] = template.HTML(m["body"].(string))
  714. // // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
  715. // //fmt.Println(m)
  716. // mapListComplete = append(mapListComplete, m)
  717. // }
  718. // rows.Close()
  719. taskForm := forms.BaseForm(forms.POST, "").SetId("taskForm").SetParam("name", "taskForm").Elements(
  720. fields.TextAreaField("Body", 30, 50).AddClass("materialize-textarea").SetLabel("Body"),
  721. fields.SubmitButton("submit", "Submit").AddClass("waves-effect waves-light btn"),
  722. )
  723. log.Println(mapListTabs[0]["id"])
  724. var firstTab int64
  725. cookie, err := r.Cookie("lastTab")
  726. if err == nil {
  727. cookieVal, err := strconv.Atoi(cookie.Value)
  728. if err != nil{
  729. }
  730. firstTab = int64(cookieVal)
  731. }else{
  732. firstTab = mapListTabs[0]["id"].(int64)
  733. }
  734. log.Println(firstTab)
  735. userIdInt, err := strconv.Atoi(userId)
  736. //"publicTasks": mapList, "privateTasks": mapListPrivate, "completeTasks": mapListComplete
  737. renderTemplate(w, "board_index_redux.html", map[string]interface{}{"UserId": userIdInt, "FirstTab": firstTab, "Tabs": mapListTabs, "Board":mapListBoard[0], "SessionId": session, "taskForm": taskForm}, r)
  738. })
  739. r.HandleFunc("/app/courses/create/", func(w http.ResponseWriter, r *http.Request) {
  740. currentUser := getUserName(r)
  741. if currentUser == "" {
  742. http.Redirect(w, r, "/register/login/?redirect=/app/courses/create/", http.StatusTemporaryRedirect)
  743. return
  744. }
  745. form := forms.BaseFormFromModel(adminModels["course"], forms.POST, "/api/courses/create/").SetParam("name", "courseForm")
  746. taskForm := forms.BaseFormFromModel(adminModels["task"], forms.POST, "").SetId("taskForm").SetParam("name", "taskForm")
  747. renderTemplate(w, "courses_create_new.html", map[string]interface{}{"form": form, "taskForm": taskForm}, r)
  748. })
  749. r.HandleFunc("/admin/{model}/", func(w http.ResponseWriter, r *http.Request) {
  750. vars := mux.Vars(r)
  751. form := forms.BaseFormFromModel(adminModels[vars["model"]], forms.POST, "")
  752. renderTemplate(w, "admin_model.html", map[string]interface{}{"form": form}, r)
  753. })
  754. r.HandleFunc("/admin/{model}/add/", func(w http.ResponseWriter, r *http.Request) {
  755. vars := mux.Vars(r)
  756. form := forms.BaseFormFromModel(adminModels[vars["model"]], forms.POST, "")
  757. renderTemplate(w, "admin_create_model.html", map[string]interface{}{"form": form, "model": vars["model"]}, r)
  758. })
  759. r.HandleFunc("/admin/{model}/{id:[0-9]+}/", func(w http.ResponseWriter, r *http.Request) {
  760. //TODO Make this interface work on dynamic typing
  761. vars := mux.Vars(r)
  762. var objectDoesNotExist = false
  763. var currentModel Course
  764. query := fmt.Sprintf("SELECT * FROM %v WHERE %v.id='%v';", vars["model"], vars["model"], vars["id"])
  765. rows, err := db.MainDatabase.Query(query)
  766. if err != nil {
  767. log.Fatal(err)
  768. }
  769. n, err := dbr.Load(rows, &currentModel)
  770. if err != nil {
  771. log.Fatal(err)
  772. }
  773. if n != 1 {
  774. objectDoesNotExist = true
  775. }
  776. form := forms.BaseFormFromModel(currentModel, forms.POST, "")
  777. data := map[string]interface{}{"form": form, "model": vars["model"]}
  778. if objectDoesNotExist {
  779. data["form"] = nil
  780. }
  781. renderTemplate(w, "admin_create_model.html", data, r)
  782. })
  783. r.HandleFunc("/api/register/signup/", func(w http.ResponseWriter, r *http.Request) {
  784. firstName := r.FormValue("first_name")
  785. //lastName := r.FormValue("last_name")
  786. email := r.FormValue("email")
  787. password := r.FormValue("password")
  788. confirmPassword := r.FormValue("password_confirm")
  789. confirmTerms := r.FormValue("agree_terms")
  790. captcha := r.FormValue("g-recaptcha-response")
  791. confirmCaptcha, error := recaptcha.Confirm (getIPAdress(r), captcha)
  792. if error != nil {
  793. log.Println(error)
  794. }
  795. if confirmTerms != "true" {
  796. fmt.Fprintf(w, "{\"Error\":\"Please agree to the Terms of Use and Privacy Policy.\"}")
  797. return
  798. }
  799. if !confirmCaptcha {
  800. fmt.Fprintf(w, "{\"Error\":\"Please fill out captcha.\"}")
  801. return
  802. }
  803. if password != confirmPassword {
  804. log.Println("Passwords do not match.")
  805. fmt.Fprintf(w, "{\"Error\":\"Your password must match.\"}")
  806. return
  807. }
  808. err := checkmail.ValidateFormat(email)
  809. if err != nil {
  810. fmt.Println(err)
  811. fmt.Fprintf(w, "{\"Error\":\"Please enter a valid email address (example@example.com).\"}")
  812. return
  813. }
  814. didCreate, id := auth.CreateUser(email, "maxmarksjr", password, firstName, "foo.db")
  815. if !didCreate {
  816. fmt.Fprintf(w, "{\"Error\":\"Account Exists\"}")
  817. return
  818. }
  819. setSession(email,id, w)
  820. fmt.Fprintf(w, "{\"Success\":\"Account Created\"}")
  821. })
  822. r.HandleFunc("/api/register/login/", func(w http.ResponseWriter, r *http.Request) {
  823. email := r.FormValue("email")
  824. password := r.FormValue("password")
  825. didLogin, id := auth.LoginUser(email, password)
  826. if didLogin {
  827. setSession(email, id, w)
  828. fmt.Println("User Logged in")
  829. fmt.Fprintf(w, "{\"Success\":\"User Logged In\"}")
  830. } else {
  831. clearSession(w)
  832. fmt.Println("User not logged in")
  833. fmt.Fprintf(w, "{\"Error\":\"Incorrect\"}")
  834. }
  835. })
  836. r.HandleFunc("/api/tasks/delete/", func(w http.ResponseWriter, r *http.Request) {
  837. currentUser := getUserName(r)
  838. if currentUser == "" {
  839. fmt.Fprintf(w, `{"Error":"Not Authenticated"}`)
  840. return
  841. }
  842. userId := getUserId(r)
  843. task := r.FormValue("task")
  844. database := db.MainDatabase
  845. insert_row, error := database.Query(fmt.Sprintf("UPDATE task SET active=false WHERE owner=%v AND id=%v;", userId, task))
  846. if error != nil {
  847. log.Println(error)
  848. fmt.Fprintf(w, `{"Error":"Not Task Owner"}`)
  849. return
  850. }
  851. for insert_row.Next() {
  852. continue
  853. }
  854. fmt.Fprintf(w, "{\"Success\":\"User Logged In\"}")
  855. })
  856. r.HandleFunc("/api/tasks/file/", func(w http.ResponseWriter, r *http.Request) {
  857. log.Println("File Upload Started...")
  858. currentUser := getUserName(r)
  859. if currentUser == "" {
  860. fmt.Fprintf(w, `{"Error":"Not Authenticated"}`)
  861. return
  862. }
  863. userId := getUserId(r)
  864. file, handler, err := r.FormFile("fileUploadPrivate")
  865. if err != nil {
  866. log.Println(err)
  867. }
  868. defer file.Close()
  869. f, err := os.OpenFile(fmt.Sprintf("temp/%v", handler.Filename), os.O_WRONLY|os.O_CREATE, 0666)
  870. if err != nil {
  871. log.Fatal(err)
  872. }
  873. fmt.Println(f.Name()) // For example "dir/prefix054003078"
  874. io.Copy(f, file)
  875. //TODO Write the code to get the file
  876. contentType := mime.TypeByExtension(filepath.Ext(f.Name()))
  877. // Upload the file with FPutObject
  878. n, err := minioClient.FPutObject(bucketName, fmt.Sprintf("media/%v/%v", userId, handler.Filename), f.Name(), minio.PutObjectOptions{ContentType:contentType})
  879. if err != nil {
  880. log.Fatalln(err)
  881. }
  882. log.Printf("Successfully uploaded %s of size %d\n", handler.Filename, n)
  883. os.Remove(f.Name())
  884. log.Println(file)
  885. var tmpMsg Message
  886. tmpMsg.File = fmt.Sprintf("/media/%v/", userId)+handler.Filename
  887. //tmpMsg.Id = r.FormValue("signature")
  888. log.Println("File Uploading")
  889. log.Println(r.FormValue("signature"))
  890. tmpMsg.Signature = r.FormValue("signature")
  891. tmpMsg.Session = r.FormValue("session")
  892. tmpMsg.Message = r.FormValue("Message")
  893. tmpMsg.IsPublic = false
  894. tmpMsg.Tab, err = strconv.Atoi(r.FormValue("tab"))
  895. tmpMsg.Creating = true
  896. tmpMsg.Id = -1
  897. database := db.MainDatabase
  898. 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))
  899. if error != nil {
  900. log.Fatal(error)
  901. }
  902. var id int
  903. for insert_row.Next() {
  904. err := insert_row.Scan(&id)
  905. if err != nil {
  906. log.Fatal(err)
  907. }
  908. }
  909. 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))
  910. if err != nil {
  911. log.Fatal(err)
  912. }
  913. tmpMsg.Task = getColumnMap(rows)[0]
  914. tmpMsg.Id = id
  915. // Send it out to every client that is currently connected
  916. for client := range clients {
  917. if tmpMsg.Session == clientId[client]{
  918. err := client.WriteJSON(tmpMsg)
  919. if err != nil {
  920. log.Printf("error: %v", err)
  921. client.Close()
  922. delete(clients, client)
  923. }
  924. }
  925. }
  926. fmt.Fprintf(w, "{\"Success\":\"User Logged In\"}")
  927. })
  928. r.HandleFunc("/api/tasks/file/public/", func(w http.ResponseWriter, r *http.Request) {
  929. currentUser := getUserName(r)
  930. if currentUser == "" {
  931. fmt.Fprintf(w, `{"Error":"Not Authenticated"}`)
  932. return
  933. }
  934. userId := getUserId(r)
  935. file, handler, err := r.FormFile("fileUploadPublic")
  936. if err != nil {
  937. log.Println(err)
  938. }
  939. defer file.Close()
  940. f, err := os.OpenFile(fmt.Sprintf("temp/%v", handler.Filename), os.O_WRONLY|os.O_CREATE, 0666)
  941. if err != nil {
  942. log.Fatal(err)
  943. }
  944. fmt.Println(f.Name()) // For example "dir/prefix054003078"
  945. io.Copy(f, file)
  946. //TODO Write the code to get the file
  947. contentType := "application/octet-stream"
  948. // Upload the file with FPutObject
  949. n, err := minioClient.FPutObject(bucketName, fmt.Sprintf("media/%v/%v", userId, handler.Filename), f.Name(), minio.PutObjectOptions{ContentType:contentType})
  950. if err != nil {
  951. log.Fatalln(err)
  952. }
  953. log.Printf("Successfully uploaded %s of size %d\n", handler.Filename, n)
  954. os.Remove(f.Name())
  955. log.Println(file)
  956. // os.Mkdir(fmt.Sprintf("../public/static/media/%v/", userId), 0777)
  957. // f, err := os.OpenFile(fmt.Sprintf("../public/static/media/%v/", userId) + handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
  958. // defer f.Close()
  959. // io.Copy(f, file)
  960. // log.Println(file)
  961. //currentSession := r.FormValue("session")
  962. var tmpMsg Message
  963. tmpMsg.File = fmt.Sprintf("/media/%v/", userId)+handler.Filename
  964. //tmpMsg.Id = r.FormValue("signature")
  965. log.Println("File Uploading")
  966. log.Println(r.FormValue("signature"))
  967. tmpMsg.Signature = r.FormValue("signature")
  968. tmpMsg.Session = r.FormValue("session")
  969. tmpMsg.Message = r.FormValue("Message")
  970. tmpMsg.IsPublic = true
  971. tmpMsg.Tab, err = strconv.Atoi(r.FormValue("tab"))
  972. tmpMsg.Creating = true
  973. tmpMsg.Id = -1
  974. database := db.MainDatabase
  975. 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))
  976. if error != nil {
  977. log.Fatal(error)
  978. }
  979. var id int
  980. for insert_row.Next() {
  981. err := insert_row.Scan(&id)
  982. if err != nil {
  983. log.Fatal(err)
  984. }
  985. }
  986. 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))
  987. if err != nil {
  988. log.Fatal(err)
  989. }
  990. tmpMsg.Task = getColumnMap(rows)[0]
  991. tmpMsg.Id = id
  992. // Send it out to every client that is currently connected
  993. for client := range clients {
  994. if tmpMsg.Session == clientId[client]{
  995. err := client.WriteJSON(tmpMsg)
  996. if err != nil {
  997. log.Printf("error: %v", err)
  998. client.Close()
  999. delete(clients, client)
  1000. }
  1001. }
  1002. }
  1003. fmt.Fprintf(w, "{\"Success\":\"User Logged In\"}")
  1004. })
  1005. r.HandleFunc("/api/courses/create/", func(w http.ResponseWriter, r *http.Request) {
  1006. currentUser := getUserName(r)
  1007. if currentUser == "" {
  1008. fmt.Fprintf(w, `{"Error":"Not Authenticated"}`)
  1009. return
  1010. }
  1011. name := r.FormValue("Name")
  1012. description := r.FormValue("Description")
  1013. courseType := r.FormValue("Type")
  1014. catagory := r.FormValue("Catagory")
  1015. isPublic := r.FormValue("IsPublic")
  1016. database := db.MainDatabase
  1017. 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))
  1018. if error != nil {
  1019. log.Println(error)
  1020. fmt.Fprintf(w, "{\"Error\":\"Server Error\"}")
  1021. return
  1022. }
  1023. for insert_row.Next() {
  1024. continue
  1025. }
  1026. fmt.Fprintf(w, "{\"Success\":\"Course Created\"}")
  1027. })
  1028. r.HandleFunc("/api/boards/add/", func(w http.ResponseWriter, r *http.Request) {
  1029. userId := getUserId(r)
  1030. if userId == "" {
  1031. return
  1032. }
  1033. boardId := r.FormValue("boardId")
  1034. database := db.MainDatabase
  1035. insertQuery := fmt.Sprintf("INSERT INTO user_boards VALUES (%v, %v);", userId, boardId)
  1036. log.Println(insertQuery)
  1037. insert_row, error := database.Query(insertQuery)
  1038. if error != nil {
  1039. log.Println(error)
  1040. fmt.Fprintf(w, "{\"Error\":\"Server Error\"}")
  1041. return
  1042. }
  1043. for insert_row.Next() {
  1044. continue
  1045. }
  1046. fmt.Fprintf(w, "{\"Success\":\"Board Added\"}")
  1047. })
  1048. r.HandleFunc("/api/survey/intro/", func(w http.ResponseWriter, r *http.Request) {
  1049. currentSurveySession := getSurveySession(r)
  1050. fmt.Printf("\nHello World My Name is %v\n", currentSurveySession)
  1051. questionId := r.FormValue("question")
  1052. question := survey.Get_Survey_Question(questionId)
  1053. if questionId == "4" {
  1054. if err := r.ParseForm(); err != nil {
  1055. // handle error
  1056. }
  1057. fmt.Println(r.PostForm["mainInput"])
  1058. response := survey.Process_Task_Answer(r.PostForm["mainInput"], question, questionId, currentSurveySession)
  1059. if response != "" {
  1060. fmt.Fprintf(w, response)
  1061. } else {
  1062. fmt.Fprintf(w, "{\"Error\":\"Incorrect\"}")
  1063. }
  1064. }else if questionId == "5"{
  1065. //name := results["name"][0]
  1066. //Check if the user is logged in
  1067. survey.SessionList[currentSurveySession]["mainInput"] = r.PostForm["mainInput"]
  1068. survey.SessionList[currentSurveySession]["password"] = r.PostForm["password"]
  1069. currentUser := getUserName(r)
  1070. if currentUser == "" {
  1071. fmt.Fprintf(w, "{\"Error\":\"No Auth\"}")
  1072. return
  1073. }
  1074. userId := getUserId(r)
  1075. results := survey.SessionList[currentSurveySession]
  1076. vision := sanitizeInput(results["vision"][0])
  1077. tasks := results["tasks"]
  1078. boardName := sanitizeInput(r.PostForm["mainInput"][0])
  1079. password := sanitizeInput(r.PostForm["password"][0])
  1080. projectType := sanitizeInput(results["type"][0])
  1081. sessionId := xid.New()
  1082. 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)
  1083. database := db.MainDatabase
  1084. insert_row, error := database.Query(insertQuery)
  1085. var boardId int
  1086. if error != nil {
  1087. log.Println(error)
  1088. fmt.Fprintf(w, "{\"Error\":\"Server Error\"}")
  1089. return
  1090. }
  1091. for insert_row.Next() {
  1092. err := insert_row.Scan(&boardId)
  1093. if err != nil {
  1094. log.Fatal(err)
  1095. }
  1096. }
  1097. insertQuery = fmt.Sprintf("INSERT INTO user_boards (auth_user, boards) VALUES (%v, %v);", userId, boardId)
  1098. log.Println(insertQuery)
  1099. insert_row, error = database.Query(insertQuery)
  1100. if error != nil {
  1101. log.Println(error)
  1102. fmt.Fprintf(w, "{\"Error\":\"Server Error\"}")
  1103. return
  1104. }
  1105. for insert_row.Next() {
  1106. continue
  1107. }
  1108. insertQuery = fmt.Sprintf("INSERT INTO tab (title, board) VALUES ('Main', %v) RETURNING id;", boardId)
  1109. log.Println(insertQuery)
  1110. insert_row, error = database.Query(insertQuery)
  1111. var tabId int
  1112. if error != nil {
  1113. log.Println(error)
  1114. fmt.Fprintf(w, "{\"Error\":\"Server Error\"}")
  1115. return
  1116. }
  1117. for insert_row.Next() {
  1118. err := insert_row.Scan(&tabId)
  1119. if err != nil {
  1120. log.Fatal(err)
  1121. }
  1122. }
  1123. insertQuery = "INSERT INTO task (body, board, owner, isPublic, complete, tab) VALUES %v;"
  1124. var buffer bytes.Buffer
  1125. for index := range tasks {
  1126. currentStr := fmt.Sprintf(`('%v', '%v', %v, false, true, %v)`, sanitizeInput(tasks[index]), sessionId, userId, tabId)
  1127. buffer.WriteString(currentStr)
  1128. if index != len(tasks) - 1 {
  1129. buffer.WriteString(",")
  1130. }
  1131. }
  1132. insertQuery = fmt.Sprintf(insertQuery, buffer.String())
  1133. fmt.Println(insertQuery)
  1134. insert_row, error = database.Query(insertQuery)
  1135. if error != nil {
  1136. log.Println(error)
  1137. }
  1138. for insert_row.Next() {
  1139. continue
  1140. }
  1141. fmt.Fprintf(w, "{\"Done\":\"Complete\"}")
  1142. return
  1143. }else{
  1144. answer := r.FormValue("mainInput")
  1145. fmt.Println(answer)
  1146. fmt.Printf(questionId)
  1147. response := survey.Process_Intro_Answer(answer, question, questionId, currentSurveySession)
  1148. fmt.Println(response)
  1149. fmt.Println("========================")
  1150. //fmt.Println(question[0])
  1151. //fmt.Println(response)
  1152. if response != "" {
  1153. fmt.Fprintf(w, response)
  1154. } else {
  1155. fmt.Fprintf(w, "{\"Error\":\"Incorrect\"}")
  1156. }
  1157. }
  1158. //fmt.Fprintf(w, "{\"Error\":\"Incorrect\"}")
  1159. })
  1160. r.HandleFunc("/app/board/finish/", func(w http.ResponseWriter, r *http.Request) {
  1161. currentSurveySession := getSurveySession(r)
  1162. //Check if the user is logged in
  1163. currentUser := getUserName(r)
  1164. if currentUser == "" {
  1165. fmt.Fprintf(w, "{\"Error\":\"No Auth\"}")
  1166. return
  1167. }
  1168. results := survey.SessionList[currentSurveySession]
  1169. userId := getUserId(r)
  1170. fmt.Printf("\n\n%v\n\n", results)
  1171. vision := sanitizeInput(results["vision"][0])
  1172. tasks := results["tasks"]
  1173. boardName := sanitizeInput(results["mainInput"][0])
  1174. password := sanitizeInput(results["password"][0])
  1175. projectType := sanitizeInput(results["type"][0])
  1176. sessionId := xid.New()
  1177. 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)
  1178. log.Println(insertQuery)
  1179. database := db.MainDatabase
  1180. insert_row, error := database.Query(insertQuery)
  1181. var boardId int
  1182. if error != nil {
  1183. log.Println(error)
  1184. fmt.Fprintf(w, "{\"Error\":\"Server Error\"}")
  1185. return
  1186. }
  1187. for insert_row.Next() {
  1188. err := insert_row.Scan(&boardId)
  1189. if err != nil {
  1190. log.Fatal(err)
  1191. }
  1192. }
  1193. insertQuery = fmt.Sprintf("INSERT INTO user_boards VALUES (%v, %v);", userId, boardId)
  1194. log.Println(insertQuery)
  1195. insert_row, error = database.Query(insertQuery)
  1196. if error != nil {
  1197. log.Println(error)
  1198. fmt.Fprintf(w, "{\"Error\":\"Server Error\"}")
  1199. return
  1200. }
  1201. for insert_row.Next() {
  1202. continue
  1203. }
  1204. insertQuery = fmt.Sprintf("INSERT INTO tab (title, board) VALUES ('Main', %v) RETURNING id;", boardId)
  1205. log.Println(insertQuery)
  1206. insert_row, error = database.Query(insertQuery)
  1207. var tabId int
  1208. if error != nil {
  1209. log.Println(error)
  1210. fmt.Fprintf(w, "{\"Error\":\"Server Error\"}")
  1211. return
  1212. }
  1213. for insert_row.Next() {
  1214. err := insert_row.Scan(&tabId)
  1215. if err != nil {
  1216. log.Fatal(err)
  1217. }
  1218. }
  1219. insertQuery = "INSERT INTO task (body, board, owner, isPublic, complete, tab) VALUES %v;"
  1220. var buffer bytes.Buffer
  1221. for index := range tasks {
  1222. currentStr := fmt.Sprintf(`('%v', '%v', %v, false, true, %v)`, sanitizeInput(tasks[index]), sessionId, userId, tabId)
  1223. buffer.WriteString(currentStr)
  1224. if index != len(tasks) - 1 {
  1225. buffer.WriteString(",")
  1226. }
  1227. }
  1228. insertQuery = fmt.Sprintf(insertQuery, buffer.String())
  1229. fmt.Println(insertQuery)
  1230. insert_row, error = database.Query(insertQuery)
  1231. if error != nil {
  1232. log.Println(error)
  1233. }
  1234. for insert_row.Next() {
  1235. continue
  1236. }
  1237. http.Redirect(w, r, fmt.Sprintf("/app/boards/%v/",sessionId), http.StatusTemporaryRedirect)
  1238. return
  1239. })
  1240. r.HandleFunc("/app/dashboard/", func(w http.ResponseWriter, r *http.Request) {
  1241. currentUser := getUserName(r)
  1242. if currentUser == "" {
  1243. http.Redirect(w, r, "/register/login/?redirect=/app/dashboard/", http.StatusTemporaryRedirect)
  1244. return
  1245. }

Large files files are truncated, but you can click here to view the full file