I am creating a small quiz app using react and go. Here is my golang backend code. I'm making sessions using gorilla and routes using gin. When I print session.Values in my initial request(login), all the values are getting printed properly. But in other requests, session.Values comes out to be nil. I'm attaching the backend code here.
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/gorilla/sessions"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite" // If you want to use mysql or any other db, replace this line
)
var db *gorm.DB // declaring the db globally
var err error
var store = sessions.NewCookieStore([]byte("secret"))
type Person struct {
ID uint `json:"id"`
FirstName string `json:"firstname"`
LastName string `json:"lastname"`
Email string `json:"email"`
Password string `json:"password"`
}
type Quiz struct {
ID uint `json:"id"`
Name string `json:"name"`
Genre string `json:"genre"`
}
type Question struct {
ID uint `json:"id"`
Question string `json:"question"`
Opt1 string `json:"opt1"`
Opt2 string `json:"opt2"`
Opt3 string `json:"opt3"`
Opt4 string `json:"opt4"`
Ans1 bool `json:"ans1"`
Ans2 bool `json:"ans2"`
Ans3 bool `json:"ans3"`
Ans4 bool `json:"ans4"`
QuizId uint `json:"QuizID,string"`
}
func main() {
db, err = gorm.Open("sqlite3", "./gorm.db")
if err != nil {
fmt.Println(err)
}
defer db.Close()
db.AutoMigrate(&Person{})
db.AutoMigrate(&Quiz{})
db.AutoMigrate(&Question{})
r := gin.Default()
r.POST("/people", CreateAccount)
r.POST("/authenticate/", Login)
private := r.Group("/private")
private.Use(AuthRequired())
// {
private.GET("/quiz-list/", ViewAllQuizzes)
private.POST("/CreateQuiz/", CreateQuiz)
private.GET("/AllPeople/", ListPeople)
private.GET("/GetQuestion/:id", GetQuestion)
private.GET("/getPlayerId/", getPlayerId)
private.POST("/UpdateQuestion/:id", UpdateQuestion)
private.POST("/DeleteQuiz/:id", DeleteQuiz)
private.POST("/DeletePerson/:id", DeletePerson)
private.POST("/AddQuestion/", AddQuestion)
private.POST("/delete-question/:id", DeleteQuestion)
private.GET("/question-list/:id", ListQuestions)
// }
r.Run(":8080") // Run on port 8080
}
func AuthRequired() gin.HandlerFunc {
return func(c *gin.Context) {
fmt.Println("AuthReqAuthReqAuthReq==============================")
// session := sessions.Default(c)
session, err := store.Get(c.Request, "session-name")
fmt.Println(err)
fmt.Println("AuthRequired", err, session.Values)
if session.Values["email"] != nil {
// Continue down the chain to handler etc
c.Next()
} else {
// You'd normally redirect to login page
c.JSON(http.StatusBadRequest, "Not logged in")
}
}
}
func Login(c *gin.Context) {
var person Person
var received_person Person
c.BindJSON(&received_person)
d := db.Where("email = ?", received_person.Email).First(&person)
fmt.Println("login", d)
c.Header("access-control-allow-origin", "http://localhost:3000")
c.Header("access-control-allow-credentials", "true")
if person.Email == received_person.Email && person.Password == received_person.Password {
session, err := store.Get(c.Request, "session-name")
session.Values["email"] = person.Email
session.Values["id"] = person.ID
session.Values["logged-in"] = true
session.Values["firstName"] = person.FirstName
session.Values["lastName"] = person.LastName
session.Save(c.Request, c.Writer)
fmt.Println("login", session.Values, err)
c.JSON(200, person)
} else {
c.JSON(200, "User Not Found")
}
}
func getPlayerId(c *gin.Context) {
c.Header("access-control-allow-origin", "*") // Why am I doing this? Find out. Try running with this line commented
session, _ := store.Get(c.Request, "session-name")
fmt.Println("getID ", session.Values)
id := session.Values["id"]
c.JSON(200, id)
}
In the getPlayerId function, sessions.Values turns out to be nil.
This is for an academic assignment.