Guest User

Untitled

a guest
Oct 15th, 2017
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.41 KB | None | 0 0
  1. package config
  2.  
  3. import (
  4. "log"
  5. "net/http"
  6.  
  7. "github.com/gorilla/sessions"
  8. )
  9.  
  10. type Options struct {
  11. Path string
  12. Domain string
  13. MaxAge int
  14. Secure bool
  15. HttpOnly bool
  16. }
  17.  
  18. type Session struct {
  19. ID string
  20. Values map[interface{}]interface{}
  21. Options *Options
  22. IsNew bool
  23. }
  24.  
  25. type Store interface {
  26. Get(r *http.Request, name string) (*sessions.Session, error)
  27. New(r *http.Request, name string) (*sessions.Session, error)
  28. Save(r *http.Request, w http.ResponseWriter, s *sessions.Session) error
  29. }
  30.  
  31. var SessionsStore = sessions.NewCookieStore([]byte("secret"))
  32.  
  33. func init() {
  34. SessionsStore.Options = &sessions.Options{
  35. Domain: "localhost",
  36. Path: "/",
  37. MaxAge: 3600 * 8, // 8 hours
  38. HttpOnly: true,
  39. }
  40. }
  41.  
  42. func KeyStore() (store Store) {
  43.  
  44. log.Print("inside KeyStore")
  45. store = SessionsStore
  46. log.Print("Value of store is : ", store)
  47. return store
  48. }
  49.  
  50. package main
  51.  
  52. import (
  53. "database/sql"
  54. "fmt"
  55. "log"
  56. "net/http"
  57. "os"
  58.  
  59. _ "github.com/lib/pq"
  60. "github.com/patientplatypus/gorest/config"
  61.  
  62. "github.com/gorilla/handlers"
  63. )
  64.  
  65. const (
  66. host = "localhost"
  67. port = 5432
  68. user = "patientplatypus"
  69. password = "superdupersecretyo"
  70. dbname = "dungeon_world"
  71. )
  72.  
  73. func main() {
  74.  
  75. psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
  76. "password=%s dbname=%s sslmode=disable",
  77. "localhost", 5432, "patientplatypus", "supersecret", "dungeon_world")
  78. var err error
  79. config.DB, err = sql.Open("postgres", psqlInfo)
  80. if err != nil {
  81. panic(err)
  82. }
  83.  
  84. err = config.DB.Ping()
  85. if err != nil {
  86. panic(err)
  87. }
  88.  
  89. fmt.Println("Successfully connected~!")
  90.  
  91. router := NewRouter()
  92. os.Setenv("ORIGIN_ALLOWED", "*")
  93. headersOk := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type"})
  94. originsOk := handlers.AllowedOrigins([]string{os.Getenv("ORIGIN_ALLOWED")})
  95. methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
  96.  
  97. log.Fatal(http.ListenAndServe(":8080", handlers.CORS(originsOk, headersOk, methodsOk)(router)))
  98.  
  99. }
  100.  
  101. package main
  102.  
  103. import (
  104. "net/http"
  105.  
  106. "github.com/patientplatypus/gorest/users"
  107.  
  108. "github.com/patientplatypus/gorest/dungeon_db"
  109.  
  110. "github.com/patientplatypus/gorest/character"
  111.  
  112. "github.com/patientplatypus/gorest/createcharacter"
  113.  
  114. "github.com/gorilla/mux"
  115. )
  116.  
  117. type Route struct {
  118. Name string
  119. Method string
  120. Pattern string
  121. HandlerFunc http.HandlerFunc
  122. }
  123.  
  124. type Routes []Route
  125.  
  126. func NewRouter() *mux.Router {
  127.  
  128. router := mux.NewRouter().StrictSlash(true)
  129. for _, route := range routes {
  130. router.
  131. Methods(route.Method).
  132. Path(route.Pattern).
  133. Name(route.Name).
  134. Handler(route.HandlerFunc)
  135. }
  136.  
  137. return router
  138. }
  139.  
  140. var routes = Routes{
  141. Route{
  142. "ClassType",
  143. "POST",
  144. "/character/class",
  145. character.ClassType,
  146. },
  147. <MORE ROUTES FOLLOWING SAME PATTERN>
  148. }
  149.  
  150. package users
  151.  
  152. import (
  153. "encoding/json"
  154. "log"
  155. "net/http"
  156.  
  157. "github.com/patientplatypus/gorest/config"
  158. )
  159.  
  160. type LoginResponse struct {
  161. Status string
  162. }
  163.  
  164. type User struct {
  165. Username string
  166. Password string
  167. Id int
  168. }
  169.  
  170. func UserLogin(w http.ResponseWriter, r *http.Request) {
  171.  
  172. decoder := json.NewDecoder(r.Body)
  173.  
  174. var incomingjson User
  175. err := decoder.Decode(&incomingjson)
  176.  
  177. if err != nil {
  178. panic(err)
  179. }
  180.  
  181. username := incomingjson.Username
  182. password := incomingjson.Password
  183.  
  184. log.Print("username: ", username)
  185. log.Print("password: ", password)
  186. if username != "" && password != "" {
  187. incomingjson.Login(w, r)
  188. } else {
  189. fmt.Fprintln(w, "error username or password is blank!")
  190. }
  191. }
  192.  
  193. func (incomingjson *User) Login(w http.ResponseWriter, r *http.Request) {
  194. session, _ := config.KeyStore().Get(r, "cookie-name")
  195. log.Print("loginjson: ", incomingjson)
  196. var tempvar string
  197.  
  198. err := config.DB.QueryRow("SELECT username FROM users WHERE username=$1;", incomingjson.Username).Scan(&tempvar)
  199. log.Print("err: ", err)
  200. if err == nil {
  201. // 1 row
  202. log.Print("Found username")
  203. var passwordindatabase string
  204. config.DB.QueryRow("SELECT password FROM users WHERE username=$1;", &incomingjson.Username).Scan(&passwordindatabase)
  205. if passwordindatabase == incomingjson.Password {
  206. log.Print("username and password match!")
  207. session.Values["authenticated"] = true
  208. session.Values["username"] = &incomingjson.Username
  209. config.KeyStore().Save(r, w, session)
  210. response := LoginResponse{Status: "Success, user logged in"}
  211. json.NewEncoder(w).Encode(response)
  212. } else {
  213. log.Print("username and password don't match!")
  214. session.Values["authenticated"] = false
  215. session.Values["username"] = ""
  216. config.KeyStore().Save(r, w, session)
  217. response := LoginResponse{Status: "Failure, username and password don't match"}
  218. json.NewEncoder(w).Encode(response)
  219. }
  220. } else {
  221. //empty result or error
  222. log.Print("Username not found or there was an error: ", err)
  223. response := LoginResponse{Status: "User not found!"}
  224. json.NewEncoder(w).Encode(response)
  225. }
  226. }
  227.  
  228. package createcharacter
  229.  
  230. import (
  231. "encoding/json"
  232. "log"
  233. "net/http"
  234.  
  235. "github.com/patientplatypus/gorest/config"
  236. )
  237.  
  238. var Username string
  239. var Checkok bool
  240.  
  241.  
  242. func SessionsCheck(w http.ResponseWriter, r *http.Request) (username string, checkok bool) {
  243. store := config.KeyStore()
  244. session, _ := store.Get(r, "cookie-name")
  245. log.Print("inside sessionscheck...what is the value of stuff....")
  246. log.Print("session: ", session)
  247. log.Print("session.Values: ", session.Values)
  248. log.Print("username: ", session.Values["username"])
  249. log.Print("authenticated: ", session.Values["authenticated"])
  250. if session.Values["username"] == nil {
  251. if session.Values["authenticated"] == false {
  252. log.Print("Verboten!")
  253. http.Error(w, "Forbidden", http.StatusForbidden)
  254. return "nil", false
  255. }
  256. }
  257. return session.Values["username"].(string), true
  258. }
  259.  
  260. func NewCharacter(w http.ResponseWriter, r *http.Request) {
  261. Username, Checkok = SessionsCheck(w, r)
  262. <FUNCTION CONTINUES>
  263.  
  264. 2017/10/15 15:08:56 inside KeyStore
  265. 2017/10/15 15:08:56 Value of store is : &{[0xc42010c000] 0xc42007d5f0}
  266. 2017/10/15 15:08:56 inside sessionscheck...what is the value of stuff....
  267. 2017/10/15 15:08:56 session: &{ map[] 0xc4201316b0 true 0xc4200e0a80 cookie-name}
  268. 2017/10/15 15:08:56 session.Values: map[]
  269. 2017/10/15 15:08:56 username: <nil>
  270. 2017/10/15 15:08:56 authenticated: <nil>
  271. 2017/10/15 15:08:56 http: panic serving [::1]:53668: interface conversion: interface {} is nil, not string
  272. goroutine 13 [running]:
  273. net/http.(*conn).serve.func1(0xc42015c5a0)
  274. /usr/local/opt/go/libexec/src/net/http/server.go:1697 +0xd0
  275. panic(0x133bcc0, 0xc420061f00)
  276. /usr/local/opt/go/libexec/src/runtime/panic.go:491 +0x283
  277. github.com/patientplatypus/gorest/createcharacter.SessionsCheck(0x1540d00, 0xc42010a540, 0xc42014ea00, 0xc42011ab00, 0x3, 0xc420001680)
  278. /Users/patientplatypus/Documents/golang/src/github.com/patientplatypus/gorest/createcharacter/charactercontroller.go:31 +0x5c9
  279. github.com/patientplatypus/gorest/createcharacter.NewCharacter(0x1540d00, 0xc42010a540, 0xc42014ea00)
  280. /Users/patientplatypus/Documents/golang/src/github.com/patientplatypus/gorest/createcharacter/charactercontroller.go:35 +0x5a
  281. net/http.HandlerFunc.ServeHTTP(0x13b8690, 0x1540d00, 0xc42010a540, 0xc42014ea00)
  282. /usr/local/opt/go/libexec/src/net/http/server.go:1918 +0x44
  283. github.com/gorilla/mux.(*Router).ServeHTTP(0xc420066360, 0x1540d00, 0xc42010a540, 0xc42014ea00)
  284. /Users/patientplatypus/Documents/golang/src/github.com/gorilla/mux/mux.go:133 +0xed
  285. github.com/gorilla/handlers.(*cors).ServeHTTP(0xc42010c7e0, 0x1540d00, 0xc42010a540, 0xc42014e800)
  286. /Users/patientplatypus/Documents/golang/src/github.com/gorilla/handlers/cors.go:118 +0x5c8
  287. net/http.serverHandler.ServeHTTP(0xc42014a000, 0x1540d00, 0xc42010a540, 0xc42014e800)
  288. /usr/local/opt/go/libexec/src/net/http/server.go:2619 +0xb4
  289. net/http.(*conn).serve(0xc42015c5a0, 0x1541240, 0xc420061dc0)
  290. /usr/local/opt/go/libexec/src/net/http/server.go:1801 +0x71d
  291. created by net/http.(*Server).Serve
  292. /usr/local/opt/go/libexec/src/net/http/server.go:2720 +0x288
Add Comment
Please, Sign In to add comment