/src/main.go

https://bitbucket.org/maxmarksjr/fluxbackend
Go | 2332 lines | 1652 code | 387 blank | 293 comment | 450 complexity | b4718ee88a93fb959b156dba5c1309ea MD5 | raw 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. }
  1246. userId := getUserId(r)
  1247. // query := fmt.Sprintf("SELECT course.id, course.name, course.type, course.difficulty, course.totalLessons FROM user_courses JOIN course ON course.id = user_courses.course JOIN authentication_users ON authentication_users.id = user_courses.auth_user WHERE authentication_users.email='%v';", currentUser)
  1248. query := fmt.Sprintf("SELECT boards.id, name, vision, session FROM user_boards JOIN boards ON boards.id = user_boards.boards WHERE user_boards.auth_user = %v ORDER BY boards.id desc;", userId);
  1249. database := db.MainDatabase
  1250. rows, err := database.Query(query)
  1251. if err != nil {
  1252. log.Fatal(err)
  1253. }
  1254. cols, _ := rows.Columns()
  1255. var courses []Course
  1256. fmt.Println(courses)
  1257. var mapList []map[string]interface{}
  1258. for rows.Next() {
  1259. // Create a slice of interface{}'s to represent each column,
  1260. // and a second slice to contain pointers to each item in the columns slice.
  1261. columns := make([]interface{}, len(cols))
  1262. columnPointers := make([]interface{}, len(cols))
  1263. for i, _ := range columns {
  1264. columnPointers[i] = &columns[i]
  1265. }
  1266. fmt.Println(columnPointers)
  1267. // Scan the result into the column pointers...
  1268. if err := rows.Scan(columnPointers...); err != nil {
  1269. }
  1270. // Create our map, and retrieve the value for each column from the pointers slice,
  1271. // storing it in the map with the name of the column as the key.
  1272. m := make(map[string]interface{})
  1273. for i, colName := range cols {
  1274. val := columnPointers[i].(*interface{})
  1275. m[colName] = *val
  1276. }
  1277. // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
  1278. //fmt.Println(m)
  1279. mapList = append(mapList, m)
  1280. // courses = append(courses, Course{
  1281. // Name: m["name"].(string),
  1282. // Type: m["type"].(string),
  1283. // LessonsSections: 0,
  1284. // TotalSections: int(m["totallessons"].(int64)),
  1285. // Link: "#",
  1286. // })
  1287. }
  1288. data := map[string]interface{}{
  1289. "Boards": mapList,
  1290. }
  1291. renderTemplate(w, "dashboard.html", data, r)
  1292. })
  1293. r.HandleFunc("/register/login/", func(w http.ResponseWriter, r *http.Request) {
  1294. redirect := r.URL.Query().Get("redirect")
  1295. renderTemplate(w, "login.html", map[string]interface{}{
  1296. "RedirectUrl": redirect,
  1297. }, r)
  1298. })
  1299. r.HandleFunc("/app/board/password/", func(w http.ResponseWriter, r *http.Request) {
  1300. redirect := r.URL.Query().Get("redirect")
  1301. renderTemplate(w, "board_require_password.html", map[string]interface{}{
  1302. "RedirectUrl": fmt.Sprintf("/app/boards/%v/", redirect),
  1303. "Session": redirect,
  1304. }, r)
  1305. })
  1306. r.HandleFunc("/api/boards/password/", func(w http.ResponseWriter, r *http.Request) {
  1307. password := r.FormValue("mainInput")
  1308. session := r.FormValue("session")
  1309. database := db.MainDatabase
  1310. rows, err := database.Query(fmt.Sprintf("SELECT id FROM boards WHERE password='%v' AND session='%v';", password, session))
  1311. if err != nil {
  1312. log.Fatal(err)
  1313. }
  1314. var count = 0
  1315. for rows.Next() {
  1316. count += 1
  1317. }
  1318. if count <= 0 {
  1319. fmt.Fprintf(w, "{\"Error\":\"Your password must match.\"}")
  1320. return
  1321. }
  1322. fmt.Fprintf(w, fmt.Sprintf(`{"Success":"%v"}`, password))
  1323. })
  1324. //https://stackoverflow.com/questions/37934162/output-uuid-in-go-as-a-short-string
  1325. r.HandleFunc("/app/starting_survey/", func(w http.ResponseWriter, r *http.Request) {
  1326. currentSurveySession := getSurveySession(r)
  1327. vision := r.FormValue("mainInput")
  1328. if currentSurveySession != "" {
  1329. fmt.Printf("Found session: %v\n", currentSurveySession)
  1330. } else {
  1331. var escaper = strings.NewReplacer("9", "99", "-", "90", "_", "91")
  1332. var unescaper = strings.NewReplacer("99", "9", "90", "-", "91", "_")
  1333. sessionUUID, err := uuid.NewV4()
  1334. if err != nil {
  1335. log.Fatal(err)
  1336. }
  1337. s := escaper.Replace(base64.RawURLEncoding.EncodeToString(sessionUUID.Bytes()))
  1338. dec, err := base64.RawURLEncoding.DecodeString(unescaper.Replace(s))
  1339. sessionId := fmt.Sprintf("%x", dec)
  1340. setSurveySession(sessionId, w)
  1341. fmt.Printf("Created new session: %v\n", sessionId)
  1342. c := survey.MongoDatabase.DB("intro_survey").C("sessions")
  1343. err = c.Insert(bson.M{"sessionId": sessionId})
  1344. if err != nil {
  1345. log.Fatal(err)
  1346. }
  1347. survey.SessionList[sessionId] = make(map[string][]string)
  1348. }
  1349. renderTemplate(w, "survey.html", map[string]interface{}{
  1350. "Vision": vision,
  1351. }, r)
  1352. })
  1353. r.HandleFunc("/app/board/create/", func(w http.ResponseWriter, r *http.Request) {
  1354. currentSurveySession := getSurveySession(r)
  1355. if currentSurveySession != "" {
  1356. fmt.Printf("Found session: %v\n", currentSurveySession)
  1357. survey.SessionList[currentSurveySession] = make(map[string][]string)
  1358. } else {
  1359. var escaper = strings.NewReplacer("9", "99", "-", "90", "_", "91")
  1360. var unescaper = strings.NewReplacer("99", "9", "90", "-", "91", "_")
  1361. sessionUUID, err := uuid.NewV4()
  1362. if err != nil {
  1363. log.Fatal(err)
  1364. }
  1365. s := escaper.Replace(base64.RawURLEncoding.EncodeToString(sessionUUID.Bytes()))
  1366. dec, err := base64.RawURLEncoding.DecodeString(unescaper.Replace(s))
  1367. sessionId := fmt.Sprintf("%x", dec)
  1368. setSurveySession(sessionId, w)
  1369. fmt.Printf("Created new session: %v\n", sessionId)
  1370. c := survey.MongoDatabase.DB("intro_survey").C("sessions")
  1371. err = c.Insert(bson.M{"sessionId": sessionId})
  1372. if err != nil {
  1373. log.Fatal(err)
  1374. }
  1375. survey.SessionList[sessionId] = make(map[string][]string)
  1376. }
  1377. renderTemplate(w, "survey.html", map[string]interface{}{
  1378. "SkipFirst": true,
  1379. }, r)
  1380. })
  1381. // Configure websocket routine
  1382. http.HandleFunc("/ws", handleConnections)
  1383. // http.HandleFunc("/ws/{model}/", func(w http.ResponseWriter, r *http.Request) {
  1384. // vars := websocket.Vars(r)
  1385. // fmt.Println("Hello World")
  1386. // fmt.Println(vars["vars"])
  1387. // })
  1388. go setTemplateChangeWatcher()
  1389. go handleMessages()
  1390. // Start the server on localhost port 8000 and log any errors
  1391. log.Println("http server started on :8000")
  1392. err_listen := http.ListenAndServe(":8000", nil)
  1393. if err_listen != nil {
  1394. log.Fatal("ListenAndServe: ", err_listen)
  1395. }
  1396. }
  1397. func getColumnMap(rows *sql.Rows) (mapListComplete []map[string]interface{}){
  1398. cols, _ := rows.Columns()
  1399. for rows.Next() {
  1400. // Create a slice of interface{}'s to represent each column,
  1401. // and a second slice to contain pointers to each item in the columns slice.
  1402. columns := make([]interface{}, len(cols))
  1403. columnPointers := make([]interface{}, len(cols))
  1404. for i, _ := range columns {
  1405. columnPointers[i] = &columns[i]
  1406. }
  1407. // Scan the result into the column pointers...
  1408. if err := rows.Scan(columnPointers...); err != nil {
  1409. }
  1410. // Create our map, and retrieve the value for each column from the pointers slice,
  1411. // storing it in the map with the name of the column as the key.
  1412. m := make(map[string]interface{})
  1413. for i, colName := range cols {
  1414. val := columnPointers[i].(*interface{})
  1415. m[colName] = *val
  1416. }
  1417. // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
  1418. //fmt.Println(m)
  1419. mapListComplete = append(mapListComplete, m)
  1420. }
  1421. return mapListComplete
  1422. }
  1423. //https://husobee.github.io/golang/ip-address/2015/12/17/remote-ip-go.html
  1424. //ipRange - a structure that holds the start and end of a range of ip addresses
  1425. type ipRange struct {
  1426. start net.IP
  1427. end net.IP
  1428. }
  1429. // inRange - check to see if a given ip address is within a range given
  1430. func inRange(r ipRange, ipAddress net.IP) bool {
  1431. // strcmp type byte comparison
  1432. if bytes.Compare(ipAddress, r.start) >= 0 && bytes.Compare(ipAddress, r.end) < 0 {
  1433. return true
  1434. }
  1435. return false
  1436. }
  1437. var privateRanges = []ipRange{
  1438. ipRange{
  1439. start: net.ParseIP("10.0.0.0"),
  1440. end: net.ParseIP("10.255.255.255"),
  1441. },
  1442. ipRange{
  1443. start: net.ParseIP("100.64.0.0"),
  1444. end: net.ParseIP("100.127.255.255"),
  1445. },
  1446. ipRange{
  1447. start: net.ParseIP("172.16.0.0"),
  1448. end: net.ParseIP("172.31.255.255"),
  1449. },
  1450. ipRange{
  1451. start: net.ParseIP("192.0.0.0"),
  1452. end: net.ParseIP("192.0.0.255"),
  1453. },
  1454. ipRange{
  1455. start: net.ParseIP("192.168.0.0"),
  1456. end: net.ParseIP("192.168.255.255"),
  1457. },
  1458. ipRange{
  1459. start: net.ParseIP("198.18.0.0"),
  1460. end: net.ParseIP("198.19.255.255"),
  1461. },
  1462. }
  1463. // isPrivateSubnet - check to see if this ip is in a private subnet
  1464. func isPrivateSubnet(ipAddress net.IP) bool {
  1465. // my use case is only concerned with ipv4 atm
  1466. if ipCheck := ipAddress.To4(); ipCheck != nil {
  1467. // iterate over all our ranges
  1468. for _, r := range privateRanges {
  1469. // check if this ip is in a private range
  1470. if inRange(r, ipAddress){
  1471. return true
  1472. }
  1473. }
  1474. }
  1475. return false
  1476. }
  1477. func getIPAdress(r *http.Request) string {
  1478. for _, h := range []string{"X-Forwarded-For", "X-Real-Ip"} {
  1479. addresses := strings.Split(r.Header.Get(h), ",")
  1480. // march from right to left until we get a public address
  1481. // that will be the address right before our proxy.
  1482. for i := len(addresses) -1 ; i >= 0; i-- {
  1483. ip := strings.TrimSpace(addresses[i])
  1484. // header can contain spaces too, strip those out.
  1485. realIP := net.ParseIP(ip)
  1486. if !realIP.IsGlobalUnicast() || isPrivateSubnet(realIP) {
  1487. // bad address, go to next
  1488. continue
  1489. }
  1490. return ip
  1491. }
  1492. }
  1493. return ""
  1494. }
  1495. //https://gist.github.com/mschoebel/9398202
  1496. //Hey, don't tell anyone about these keys. They are super secret
  1497. var cookieHandler = securecookie.New(
  1498. []byte{170, 218, 150, 242, 74, 205, 63, 28, 156, 229, 161, 187, 83, 45, 188, 101, 50, 41, 39, 172, 35, 94, 233, 246, 31, 172, 196, 107, 136, 14, 121, 13, 27, 177, 229, 118, 18, 62, 129, 81, 168, 80, 1, 147, 128, 58, 26, 242, 15, 231, 45, 140, 15, 107, 45, 143, 91, 205, 249, 238, 201, 15, 155, 7},
  1499. []byte{253, 146, 211, 216, 77, 3, 0, 42, 233, 90, 117, 198, 18, 178, 226, 136, 121, 207, 160, 243, 244, 40, 69, 97, 255, 133, 215, 65, 239, 35, 100, 179},
  1500. )
  1501. func getUserName(request *http.Request) (userName string) {
  1502. if cookie, err := request.Cookie("session"); err == nil {
  1503. cookieValue := make(map[string]string)
  1504. if err = cookieHandler.Decode("session", cookie.Value, &cookieValue); err == nil {
  1505. userName = cookieValue["name"]
  1506. } else {
  1507. return ""
  1508. }
  1509. }
  1510. return userName
  1511. }
  1512. func getUserId(request *http.Request) (id string) {
  1513. if cookie, err := request.Cookie("session"); err == nil {
  1514. cookieValue := make(map[string]string)
  1515. if err = cookieHandler.Decode("session", cookie.Value, &cookieValue); err == nil {
  1516. id = cookieValue["id"]
  1517. } else {
  1518. return ""
  1519. }
  1520. }
  1521. return id
  1522. }
  1523. func setVisionCookie(vision string, response http.ResponseWriter) {
  1524. value := map[string]string{
  1525. "vision": vision,
  1526. }
  1527. if encoded, err := cookieHandler.Encode("home_vision", value); err == nil {
  1528. cookie := &http.Cookie{
  1529. Name: "home_vision",
  1530. Value: encoded,
  1531. Path: "/",
  1532. }
  1533. http.SetCookie(response, cookie)
  1534. }
  1535. }
  1536. func getVisionCookie(request *http.Request) (vision string) {
  1537. if cookie, err := request.Cookie("home_vision"); err == nil {
  1538. cookieValue := make(map[string]string)
  1539. if err = cookieHandler.Decode("home_vision", cookie.Value, &cookieValue); err == nil {
  1540. vision = cookieValue["vision"]
  1541. } else {
  1542. return ""
  1543. }
  1544. }
  1545. return vision
  1546. }
  1547. func setSurveySession(sessionId string, response http.ResponseWriter) {
  1548. value := map[string]string{
  1549. "sessionId": sessionId,
  1550. }
  1551. if encoded, err := cookieHandler.Encode("intro_session", value); err == nil {
  1552. cookie := &http.Cookie{
  1553. Name: "intro_session",
  1554. Value: encoded,
  1555. Path: "/",
  1556. }
  1557. http.SetCookie(response, cookie)
  1558. }
  1559. }
  1560. func getSurveySession(request *http.Request) (sessionId string) {
  1561. if cookie, err := request.Cookie("intro_session"); err == nil {
  1562. cookieValue := make(map[string]string)
  1563. if err = cookieHandler.Decode("intro_session", cookie.Value, &cookieValue); err == nil {
  1564. sessionId = cookieValue["sessionId"]
  1565. } else {
  1566. return ""
  1567. }
  1568. }
  1569. return sessionId
  1570. }
  1571. func setSession(userName string, id int, response http.ResponseWriter) {
  1572. value := map[string]string{
  1573. "name": userName,
  1574. "id": fmt.Sprintf("%v", id),
  1575. }
  1576. if encoded, err := cookieHandler.Encode("session", value); err == nil {
  1577. cookie := &http.Cookie{
  1578. Name: "session",
  1579. Value: encoded,
  1580. Path: "/",
  1581. }
  1582. http.SetCookie(response, cookie)
  1583. }
  1584. }
  1585. func clearSession(response http.ResponseWriter) {
  1586. cookie := &http.Cookie{
  1587. Name: "session",
  1588. Value: "",
  1589. Path: "/",
  1590. MaxAge: -1,
  1591. }
  1592. http.SetCookie(response, cookie)
  1593. }
  1594. func setTemplateChangeWatcher() {
  1595. // creates a new file watcher
  1596. watcher, err := fsnotify.NewWatcher()
  1597. if err != nil {
  1598. fmt.Println("ERROR", err)
  1599. }
  1600. defer watcher.Close()
  1601. //
  1602. done := make(chan bool)
  1603. //
  1604. go func() {
  1605. for {
  1606. select {
  1607. // watch for events
  1608. case event := <-watcher.Events:
  1609. fmt.Printf("Reloading Templates: %#v\n", event)
  1610. loadTemplates()
  1611. // watch for errors
  1612. case err := <-watcher.Errors:
  1613. fmt.Println("ERROR", err)
  1614. }
  1615. }
  1616. }()
  1617. err = watcher.Add("../public/layout")
  1618. if err != nil {
  1619. log.Fatal(err)
  1620. }
  1621. err = watcher.Add("../public/main")
  1622. if err != nil {
  1623. log.Fatal(err)
  1624. }
  1625. err = watcher.Add("../public/main/registration")
  1626. if err != nil {
  1627. log.Fatal(err)
  1628. }
  1629. err = watcher.Add("../public/main/errors")
  1630. if err != nil {
  1631. log.Fatal(err)
  1632. }
  1633. err = watcher.Add("../public/main/boards")
  1634. if err != nil {
  1635. log.Fatal(err)
  1636. }
  1637. err = watcher.Add("../public/main/courses")
  1638. if err != nil {
  1639. log.Fatal(err)
  1640. }
  1641. err = watcher.Add("../public/main/admin")
  1642. if err != nil {
  1643. log.Fatal(err)
  1644. }
  1645. <-done
  1646. }
  1647. func sanitizeInput(str string) (outStr string) {
  1648. var replacer = strings.NewReplacer("'", "''")
  1649. outStr = replacer.Replace(str)
  1650. return outStr
  1651. }
  1652. //https://hackernoon.com/golang-template-2-template-composition-and-how-to-organize-template-files-4cb40bcdf8f6
  1653. var mainTmpl = `{{define "main" }} {{ template "base" . }} {{ end }}`
  1654. var templates map[string]*template.Template
  1655. var TemplateLayoutPath = "../public/layout/"
  1656. var TemplateIncludePath = "../public/main/"
  1657. var bufpool *bpool.BufferPool
  1658. func loadTemplates() {
  1659. if templates == nil {
  1660. templates = make(map[string]*template.Template)
  1661. }
  1662. mainTemplate := template.New("main")
  1663. mainTemplate, err := mainTemplate.Parse(mainTmpl)
  1664. if err != nil {
  1665. log.Fatal(err)
  1666. }
  1667. layoutFiles, err := filepath.Glob(TemplateLayoutPath + "*.html")
  1668. if err != nil {
  1669. log.Fatal(err)
  1670. }
  1671. //Just noting how long this took. Thanks kinda dynamic variables
  1672. var includeFiles []string
  1673. filepath.Walk(TemplateIncludePath, func(path string, f os.FileInfo, _ error) error {
  1674. if !f.IsDir() {
  1675. r, err := regexp.MatchString(".html", f.Name())
  1676. if err == nil && r {
  1677. includeFiles = append(includeFiles, path)
  1678. }
  1679. }
  1680. return nil
  1681. })
  1682. if err != nil {
  1683. log.Fatal(err)
  1684. }
  1685. for _, file := range includeFiles {
  1686. fileName := filepath.Base(file)
  1687. files := append(layoutFiles, file)
  1688. templates[fileName], err = mainTemplate.Clone()
  1689. if err != nil {
  1690. log.Fatal(err)
  1691. }
  1692. templates[fileName] = template.Must(templates[fileName].ParseFiles(files...))
  1693. }
  1694. bufpool = bpool.NewBufferPool(64)
  1695. }
  1696. func renderTemplate(w http.ResponseWriter, name string, data map[string]interface{}, r *http.Request) {
  1697. tmpl, ok := templates[name]
  1698. if !ok {
  1699. http.Error(w, fmt.Sprintf("The template %s does not exist.", name),
  1700. http.StatusInternalServerError)
  1701. }
  1702. userEmail := getUserName(r)
  1703. var isLoggedIn bool
  1704. if userEmail == "" {
  1705. isLoggedIn = false
  1706. // fmt.Printf(userEmail)
  1707. } else {
  1708. isLoggedIn = true
  1709. }
  1710. baseParamters := map[string]interface{}{
  1711. "isLoggedIn": isLoggedIn,
  1712. "SiteTitle": "Paario",
  1713. }
  1714. if data != nil {
  1715. for k, v := range data {
  1716. if _, ok := data[k]; ok {
  1717. baseParamters[k] = v
  1718. }
  1719. }
  1720. }
  1721. buf := bufpool.Get()
  1722. defer bufpool.Put(buf)
  1723. err := tmpl.Execute(buf, baseParamters)
  1724. if err != nil {
  1725. http.Error(w, err.Error(), http.StatusInternalServerError)
  1726. }
  1727. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  1728. buf.WriteTo(w)
  1729. }
  1730. func handleConnections(w http.ResponseWriter, r *http.Request) {
  1731. // Upgrade initial GET request to a websocket
  1732. session := r.FormValue("sessionId")
  1733. currentUser := getUserName(r)
  1734. if currentUser == "" {
  1735. fmt.Fprintf(w, `{"Error":"Not Authenticated"}`)
  1736. }
  1737. userId := getUserId(r)
  1738. ws, err := upgrader.Upgrade(w, r, nil)
  1739. if err != nil {
  1740. log.Fatal(err)
  1741. }
  1742. // Make sure we close the connection when the function returns
  1743. defer ws.Close()
  1744. // Register our new client
  1745. clients[ws] = true
  1746. clientId[ws] = fmt.Sprintf("%v", session)
  1747. clientUser[ws] = fmt.Sprintf("%v", userId)
  1748. Global += 1
  1749. for {
  1750. var msg Message
  1751. // Read in a new message as JSON and map it to a Message object
  1752. err := ws.ReadJSON(&msg)
  1753. if err != nil {
  1754. log.Printf("error: %v", err)
  1755. delete(clients, ws)
  1756. break
  1757. }
  1758. log.Println(msg)
  1759. currentSession := clientId[ws]
  1760. log.Println(currentSession)
  1761. // Send the newly received message to the broadcast channel
  1762. var tmpMsg Message
  1763. tmpMsg = msg
  1764. currentUser := getUserName(r)
  1765. tmpMsg.OriginalQuestion = tmpMsg.Id
  1766. database := db.MainDatabase
  1767. currentUser = sanitizeInput(currentUser)
  1768. tmpMsg.Message = sanitizeInput(tmpMsg.Message)
  1769. userId := getUserId(r)
  1770. log.Printf("\n\n%v\n\n", userId)
  1771. if tmpMsg.IsTab {
  1772. if tmpMsg.Message != "" {
  1773. insert_row, error := database.Query(fmt.Sprintf("INSERT INTO tab(title, board) VALUES ('%v', %v) RETURNING id;", tmpMsg.Message, tmpMsg.Username))
  1774. if error != nil {
  1775. log.Fatal(error)
  1776. }
  1777. var id int
  1778. for insert_row.Next() {
  1779. err := insert_row.Scan(&id)
  1780. if err != nil {
  1781. log.Fatal(err)
  1782. }
  1783. }
  1784. tmpMsg.Session = currentSession
  1785. tmpMsg.IsTab = true
  1786. tmpMsg.IsPublic = true
  1787. tmpMsg.Id = id
  1788. log.Println(tmpMsg)
  1789. broadcast <- tmpMsg
  1790. }
  1791. }else{
  1792. tmpMsg.IsTab = false
  1793. if tmpMsg.Id != -1 && tmpMsg.Creating {
  1794. rows, err := database.Query(fmt.Sprintf("SELECT originalquestion FROM task WHERE originalquestion=%v AND owner=%v;", tmpMsg.Id, userId))
  1795. if err != nil {
  1796. log.Fatal(err)
  1797. }
  1798. var count = 0
  1799. for rows.Next() {
  1800. count += 1
  1801. }
  1802. if !(count > 0) {
  1803. var id int
  1804. insert_row, error := database.Query(fmt.Sprintf("INSERT INTO task(name, body, isPublic, originalquestion, board, owner, tab, file) VALUES ('%v', '%v', %v, %v, '%v', %v, %v, '%v') RETURNING id;", currentUser, tmpMsg.Message, tmpMsg.IsPublic, tmpMsg.Id, currentSession, userId, tmpMsg.Tab, tmpMsg.File))
  1805. if error != nil {
  1806. log.Fatal(error)
  1807. }
  1808. for insert_row.Next() {
  1809. err := insert_row.Scan(&id)
  1810. if err != nil {
  1811. log.Fatal(err)
  1812. }
  1813. }
  1814. rows, err = database.Query(fmt.Sprintf("SELECT task.id, task.tab, 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))
  1815. if err != nil {
  1816. log.Fatal(err)
  1817. }
  1818. tmpMsg.Task = getColumnMap(rows)[0]
  1819. tmpMsg.Id = id
  1820. //broadcast <- tmpMsg
  1821. log.Println(currentUser)
  1822. }
  1823. }else{
  1824. var id int
  1825. log.Println(fmt.Sprintf("Finding: %v", tmpMsg.Id))
  1826. rows, err := database.Query(fmt.Sprintf("SELECT id FROM task WHERE id=%v;", tmpMsg.Id))
  1827. if err != nil {
  1828. log.Fatal(err)
  1829. }
  1830. var count = 0
  1831. for rows.Next() {
  1832. count += 1
  1833. }
  1834. log.Println(fmt.Sprintf("COUNT: %v", count))
  1835. if count > 0 {
  1836. insert_row, error := database.Query(fmt.Sprintf("UPDATE task SET complete=%v WHERE id=%v;", tmpMsg.Complete, tmpMsg.Id))
  1837. if error != nil {
  1838. log.Fatal(error)
  1839. }
  1840. for insert_row.Next() {
  1841. continue
  1842. }
  1843. fmt.Println(id)
  1844. //tmpMsg.Id = id
  1845. log.Println(fmt.Sprintf("Updating: %v", tmpMsg.Id))
  1846. } else {
  1847. insert_row, error := database.Query(fmt.Sprintf("INSERT INTO task(name, body, isPublic, board, owner, tab) VALUES ('%v', '%v', %v, '%v', %v, %v) RETURNING id ;", currentUser, tmpMsg.Message, tmpMsg.IsPublic, currentSession, userId, tmpMsg.Tab))
  1848. if error != nil {
  1849. log.Fatal(error)
  1850. }
  1851. for insert_row.Next() {
  1852. err := insert_row.Scan(&id)
  1853. if err != nil {
  1854. log.Fatal(err)
  1855. }
  1856. }
  1857. 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))
  1858. if err != nil {
  1859. log.Fatal(err)
  1860. }
  1861. tmpMsg.Task = getColumnMap(rows)[0]
  1862. tmpMsg.Id = id
  1863. }
  1864. }
  1865. if (tmpMsg.IsPublic) {
  1866. rows, err := database.Query(fmt.Sprintf("SELECT name FROM boards WHERE session='%v';", currentSession))
  1867. if err != nil {
  1868. log.Fatal(err)
  1869. }
  1870. var boardName string
  1871. for rows.Next() {
  1872. err = rows.Scan(&boardName)
  1873. if err != nil {
  1874. log.Fatal(err)
  1875. }
  1876. }
  1877. rows, err = database.Query(fmt.Sprintf("SELECT fb_token FROM device JOIN user_boards ON user_boards.auth_user=device.auth_user WHERE user_boards.boards=%v AND NOT device.auth_user=%v;", tmpMsg.Username, userId))
  1878. if err != nil {
  1879. log.Println(err)
  1880. }
  1881. var regIds []string
  1882. for rows.Next() {
  1883. var reg_id string
  1884. err = rows.Scan(&reg_id)
  1885. if err != nil {
  1886. log.Fatal(err)
  1887. }
  1888. regIds = append(regIds, reg_id)
  1889. }
  1890. regJson, err := json.Marshal(regIds)
  1891. if err != nil {
  1892. log.Println("Cannot encode to JSON ", err)
  1893. }
  1894. url := "https://fcm.googleapis.com/fcm/send"
  1895. var jsonStr = []byte(fmt.Sprintf(`{"registration_ids": %v, "notification": {"title": "%v", "body": "%v: %v", "click_action":"https://paar.io/app/boards/%v/"}}`, string(regJson), boardName, tmpMsg.Task["displayname"], tmpMsg.Message, currentSession))
  1896. log.Println(string(jsonStr))
  1897. req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
  1898. req.Header.Set("Authorization", "key=AAAAskOw0U8:APA91bHWWqwO1AF_dq1MkXwpMdawR7aIx3-0kpTsrWNm01WUopc8mfbDm6JVee_Q1naJIbMQXo08Bxpc-i3kzlQRRq5954oFBUT1zZqby3U9ciQvqZjKfw4JRd1Z7N869la6Nj4gdSPJ")
  1899. req.Header.Set("Content-Type", "application/json")
  1900. client := &http.Client{}
  1901. resp, err := client.Do(req)
  1902. if err != nil {
  1903. panic(err)
  1904. }
  1905. log.Println(resp)
  1906. }
  1907. tmpMsg.Session = currentSession
  1908. //tmpMsg.Response = survey.Process_Answer(msg.Response, question)
  1909. log.Println(tmpMsg)
  1910. broadcast <- tmpMsg
  1911. log.Println(currentUser)
  1912. }
  1913. //log.Printf(msg.Email + " " + msg.Message)
  1914. }
  1915. }
  1916. func handleMessages() {
  1917. for {
  1918. // Grab the next message from the broadcast channel
  1919. msg := <- broadcast
  1920. fmt.Println(msg)
  1921. // Send it out to every client that is currently connected
  1922. for client := range clients {
  1923. if msg.IsPublic{
  1924. if msg.Session == clientId[client]{
  1925. err := client.WriteJSON(msg)
  1926. if err != nil {
  1927. log.Printf("error: %v", err)
  1928. client.Close()
  1929. delete(clients, client)
  1930. }
  1931. }
  1932. }else{
  1933. log.Println(msg.Task["owner"])
  1934. if msg.Session == clientId[client] && fmt.Sprintf("%v", msg.Task["owner"]) == clientUser[client]{
  1935. err := client.WriteJSON(msg)
  1936. if err != nil {
  1937. log.Printf("error: %v", err)
  1938. client.Close()
  1939. delete(clients, client)
  1940. }
  1941. }
  1942. }
  1943. }
  1944. }
  1945. }