Friday, April 26, 2024
HomeGolangAssist cookie redirect - Code Evaluate

Assist cookie redirect – Code Evaluate


Hallo Everybody, i cant appear to repair this subject, i’ve a golang web site the connection works and makes session however i wish to use cookies to redirect to reserving. i hope somebody can assist me i cant appear to get the redirect to work, i would like it to work so it checks the person makes a id and makes session then i ought to test if that went proper after which make cookie to and redirect from login to reserving:

Github: GitHub – KSCHNAPPIEN/golang-web

bundle predominant

import (
“database/sql”
“encoding/json”
“fmt”
“io/ioutil”
“log”
“internet/http”
“os”
“time”

_ "github.com/go-sql-driver/mysql"
"github.com/gorilla/periods"
_ "github.com/gorilla/periods"

)

sort DatabaseConfig struct {
Username string json:"person"
Password string json:"password"
Host string json:"host"
Port int json:"port"
Database string json:"dbname"
}

var id bool
var dbc string
var userID int
var retailer = periods.NewCookieStore([]byte(“logging succes secrect key”))

func logError(err error) {
if err != nil {
log.Println(err)
}
}

func predominant() {
logFile, err := os.OpenFile(“errors.log”, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
log.Println(err)
}
defer logFile.Shut()

log.SetOutput(logFile)

mux := http.NewServeMux()
// route naar url
mux.HandleFunc("https://discussion board.golangbridge.org/", RootHandler)

mux.HandleFunc("https://discussion board.golangbridge.org/Locatie", LocatieHandler)

mux.HandleFunc("/Login", LoginHandler)

mux.HandleFunc("/Reserving", BookingHandler)
mux.HandleFunc("/Logout", LogoutHandler)

// learn json file
configBytes, err := ioutil.ReadFile("Db.json")
if err != nil {
	logError(err)
}

// organising new struct
var config DatabaseConfig
if err := json.Unmarshal(configBytes, &config); err != nil {
	log.Println(err)
}

// make connection database
dbc = fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", config.Username, config.Password, config.Host, config.Port, config.Database)
db, err := sql.Open("mysql", dbc)
if err != nil {
	logError(err)
}
defer db.Shut()

if err := db.Ping(); err != nil {
	log.Println(err)
}

http.ListenAndServe(":8080", mux)

}

sort LoginResponse struct {
Success bool
UserID int
}

func checkLogin(w http.ResponseWriter, r *http.Request) LoginResponse {
username := r.FormValue(“username”)
password := r.FormValue(“password”)

db, err := sql.Open("mysql", dbc)
if err != nil {
	log.Println(err)
	return LoginResponse{Success: false, UserID: -1}
}
defer db.Shut()

err = db.QueryRow("SELECT id FROM customers WHERE username=? AND password=?", username, password).Scan(&userID)
if err != nil {
	log.Println(err)
	return LoginResponse{Success: false, UserID: -1}
}
sessionID := createSession(userID)
if sessionID == "" {
	log.Println("Error creating session")
	return LoginResponse{Success: false, UserID: -1}
}
sessionCookie := &http.Cookie{Title: "session_id", Worth: sessionID, Path: "https://discussion board.golangbridge.org/", Expires: time.Now().Add(time.Period(24) * time.Hour)}
http.SetCookie(w, sessionCookie)
return LoginResponse{Success: true, UserID: userID}

}

func RootHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, <h1>Fonteyn Vakantieparken</h1> <p>Vakantie parken voor een onvergeetelijke vakantie.</p> <ul> <li><a href="https://discussion board.golangbridge.org/Locatie">Locatie</a></li> <li><a href="http://discussion board.golangbridge.org/Login">Login</a></li> </ul> )
}

func LocatieHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, <h1>Locatie</h1> <p>Wij zijn beschikbaar in meerder landen.</p> <ul> <li><a href="https://discussion board.golangbridge.org/">Dwelling</a></li> <li><a href="http://discussion board.golangbridge.org/Login">Login</a></li> </ul> )
}
func createSession(userID int) string {
// Create a brand new session within the database and return the session ID
db, err := sql.Open(“mysql”, dbc)
if err != nil {
log.Println(err)
return “”
}
defer db.Shut()

// Create a novel session ID
sessionID := fmt.Sprintf("%d_percentd", userID, time.Now().UnixNano())
_, err = db.Exec("INSERT INTO periods (user_id, start_time, end_time) VALUES (?, NOW(), NOW())", userID)
if err != nil {
	log.Println(err)
	return ""
}

return sessionID

}
func LoginHandler(w http.ResponseWriter, r *http.Request) {
session, err := retailer.Get(r, “session-name”)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return

}
session.Values["logged_in"] = false

session.Save(r, w)
if r.Technique == http.MethodPost {
	loginResponse := checkLogin(w, r)
	if loginResponse.Success {
		http.Redirect(w, r, "/Reserving", http.StatusFound)
		return
	}
}
fmt.Fprintln(w, `
    <h1>Fonteyn Vakantieparken</h1>
    <p>Vakantie parken voor een onvergeetelijke vakantie.</p>
    <type motion="/Login" technique="submit">
        <label for="username">Username:</label>
        <enter sort="textual content" id="username" identify="username">
        <br>
        <label for="password">Password:</label>
        <enter sort="password" id="password" identify="password">
        <br><br>
        <enter sort="submit" worth="Submit">
    </type>
`)

}

func LogoutHandler(w http.ResponseWriter, r *http.Request) {
sessionCookie, _ := r.Cookie(“session_id”)
sessionCookie.MaxAge = -1
http.SetCookie(w, sessionCookie)
http.Redirect(w, r, “/”, http.StatusFound)
}

func BookingHandler(w http.ResponseWriter, r *http.Request) {
// Verify if the person is logged in
session, err := retailer.Get(r, “session-name”)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Als de gebruiker niet is ingelogd, verwijs de gebruiker door naar de inlogpagina
if session.Values[“logged_in”] != true {
http.Redirect(w, r, “/login”, http.StatusFound)
return
}
}

func validateSession(w http.ResponseWriter, r *http.Request, sessionID string) bool {
db, err := sql.Open(“mysql”, dbc)
if err != nil {
log.Println(err)
return false
}
defer db.Shut()

var userID int
err = db.QueryRow("SELECT user_id FROM periods WHERE id = ? AND end_time > NOW()", sessionID).Scan(&userID)
if err != nil {
	log.Println(err)
	return false
}
if userID > 0 {
	session, err1 := retailer.Get(r, "session-name")

	if err1 != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return false
	}
	session.Values["logged_in"] = true
	session.Save(r, w)
	http.Redirect(w, r, "/reserving", http.StatusFound)
	return true
} else {
	return false
}

}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments