here’s my code:
`
package main
import (
"database/sql"
"fmt"
"github.com/go-sql-driver/mysql"
"golang.org/x/crypto/bcrypt"
"html/template"
"log"
"net/http"
"strconv"
"time"
)
var (
err error
db *sql.DB
templ *template.Template
adtempl *template.Template
//cookie *http.Cookie
ID int64
)
type PageData struct {
Title string
IsAuth bool
Id int
Username string
Password string
Description string
Created_at mysql.NullTime
Updated_at mysql.NullTime
AdminD int
}
func init() {
templ, err = templ.ParseGlob("templates/*.html")
if err != nil {
log.Fatalln(err.Error())
}
adtempl, err = adtempl.ParseGlob("templates/admin/*.html")
if err != nil {
log.Fatalln(err.Error())
}
}
func main() {
handleDbConnection()
http.HandleFunc("/", index)
http.HandleFunc("/login", login)
//http.HandleFunc("/admin", admin)
http.HandleFunc("/create", createUser)
http.HandleFunc("/read", readUser)
http.HandleFunc("/update", updateUser)
http.HandleFunc("/delete", deleteUser)
http.Handle("/assets/", http.FileServer(http.Dir("."))) //serve other files in assets dir
http.Handle("/favicon.ico", http.NotFoundHandler())
fmt.Println("server running on port :8080")
http.ListenAndServe(":8080", nil)
}
func index(res http.ResponseWriter, req *http.Request) {
cookie, err := req.Cookie("logged-in")
if err == http.ErrNoCookie{
cookie = &http.Cookie{
Name: "logged-in",
Value: "0",
}
}
title := "Home || cb_net sessions"
var isAuth bool
var pd = PageData{Title: title, IsAuth: isAuth}
if cookie.Value == strconv.Itoa(1) {
err = adtempl.ExecuteTemplate(res, "index.html", pd)
if err != nil {
log.Fatalln(err.Error(),"no admin index")
}
fmt.Println("success")
} else if cookie.Value == strconv.Itoa(2) {
err = templ.ExecuteTemplate(res, "index.html", pd)
if err != nil {
log.Fatalln(err.Error(),"no user index")
}
fmt.Println("success")
} else {
isAuth = false
}
err = templ.ExecuteTemplate(res, "index.html", pd)
if err != nil {
log.Fatalln(err.Error())
}
//pd = append(pd, PageData{Title: title, IsAuth: isAuth})
}
func handleDbConnection() {
// Create an sql.DB and check for errors
db, err = sql.Open("mysql", "root:elemie@/GoStaffManager")
if err != nil {
panic(err.Error())
}
// Test the connection to the database
err = db.Ping()
if err != nil {
panic(err.Error())
}
}
func login(res http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
err = templ.ExecuteTemplate(res, "login.html", nil)
if err != nil {
fmt.Sprint("error", err)
}
return
}
// query
rows, err := db.Query("SELECT username,password,is_admin FROM new_table")
if err != nil {
log.Println(err.Error())
http.Error(res, "there was an error", http.StatusInternalServerError)
return
}
var username = req.FormValue("username")
password := req.FormValue("password")
var pword string
var isAdmin int
for rows.Next() {
err = rows.Scan(&username, &pword, &isAdmin)
if err != nil {
log.Println(err)
http.Error(res, "there was an error", http.StatusInternalServerError)
return
}
if isAdmin == 1 {
// Validate the password
err = bcrypt.CompareHashAndPassword([]byte(pword), []byte(password))
// If wrong password redirect to the login
if err != nil {
fmt.Println("invalid")
http.Redirect(res, req, "/login", 301)
return
}
cookie := &http.Cookie{
Name: "logged-in",
Value: "1",
}
http.SetCookie(res, cookie)
http.Redirect(res, req, "/", 302)
return
} else {
// Validate the password
err = bcrypt.CompareHashAndPassword([]byte(pword), []byte(password))
// If wrong password redirect to the login
if err != nil {
fmt.Println("invalid")
http.Redirect(res, req, "/login", 301)
return
}
cookie := &http.Cookie{
Name: "logged-in",
Value: "2",
}
http.SetCookie(res, cookie)
http.Redirect(res, req, "/", 302)
return
}
}
}
func createUser(res http.ResponseWriter, req *http.Request) {
//insert into db
stmt, err := db.Prepare("INSERT new_table SET username=?, password=?, created_at=?, updated_at=?, is_admin=?")
if err != nil {
log.Println(err)
http.Error(res, "there was an error", http.StatusInternalServerError)
return
}
if req.Method != "POST" {
adtempl.ExecuteTemplate(res, "create.html", nil)
return
}
username := req.FormValue("username")
password := req.FormValue("password")
isAdmin := req.FormValue("admin")
createdAt := time.Now()
updatedAt := time.Now()
var admin_chk int
if isAdmin == "on" {
admin_chk = 1
} else {
admin_chk = 0
}
var user string
err = db.QueryRow("SELECT username FROM new_table WHERE username=?", username).Scan(&user)
switch {
//username is available
case err == sql.ErrNoRows:
securedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
log.Println(err)
http.Error(res, "there was an error", http.StatusInternalServerError)
return
}
rs, err := stmt.Exec(username, securedPassword, createdAt, updatedAt, admin_chk)
if err != nil {
log.Println(err)
http.Error(res, "there was an error", http.StatusInternalServerError)
return
}
id, err := rs.LastInsertId()
if err != nil {
log.Println(err)
http.Error(res, "there was an error", http.StatusInternalServerError)
return
}
ID = getID(id).(int64)
res.Write([]byte("user successfully created!"))
fmt.Println("user: ",username," with ID: ",id," successfully created!")
return
case err != nil:
http.Error(res, err.Error(), 500)
return
default:
http.Redirect(res, req, "/create", 301)
}
}
func readUser(res http.ResponseWriter, req *http.Request) {
// query
rows, err := db.Query("SELECT * FROM new_table")
if err != nil {
log.Println(err)
http.Error(res, "there was an error", http.StatusInternalServerError)
return
}
var id int
var username string
var password string
var created_at mysql.NullTime
var updated_at mysql.NullTime
var isAdmin int
/*if req.Method != "POST" {
}*/
var ps []PageData
for rows.Next() {
err = rows.Scan(&id, &username, &password, &created_at, &updated_at, &isAdmin)
if err != nil {
log.Println(err)
http.Error(res, "there was an error", http.StatusInternalServerError)
return
}
ps = append(ps, PageData{Id: id, Username: username, Password: password, Created_at: created_at, Updated_at: updated_at, AdminD: isAdmin})
//return
}
adtempl.ExecuteTemplate(res, "read.html", ps)
}
func updateUser(res http.ResponseWriter, req *http.Request) {
//select id's
rows, err := db.Query("SELECT id FROM new_table")
if err != nil {
log.Println(err)
http.Error(res, "there was an error", http.StatusInternalServerError)
return
}
var user = req.FormValue("ids")
var newUsername = req.FormValue("username")
var ps []PageData
id, err := strconv.Atoi(user)
for rows.Next() {
err = rows.Scan(&id)
if err != nil {
log.Println(err)
http.Error(res, "there was an error", http.StatusInternalServerError)
return
}
ps = append(ps, PageData{Id: id})
}
stmt, err := db.Prepare("UPDATE new_table SET username=?, updated_at=? WHERE id=?")
if err != nil {
log.Println(err)
http.Error(res, "there was an error", http.StatusInternalServerError)
return
}
rs, err := stmt.Exec(newUsername,time.Now(), id)
if err != nil {
log.Println(err)
http.Error(res, "there was an error", http.StatusInternalServerError)
return
}
affect, err := rs.RowsAffected()
if err != nil {
log.Println(err)
http.Error(res, "there was an error", http.StatusInternalServerError)
return
}
if req.Method != "POST" {
adtempl.ExecuteTemplate(res, "update.html", ps)
return
}
fmt.Println("row :",affect," affected")
}
func deleteUser(res http.ResponseWriter, req *http.Request) {
//select id's
rows, err := db.Query("SELECT id FROM new_table")
if err != nil {
log.Println(err)
http.Error(res, "there was an error", http.StatusNoContent)
return
}
var user = req.FormValue("ids")
var ps []PageData
id, err := strconv.Atoi(user)
for rows.Next() {
err = rows.Scan(&id)
if err != nil {
log.Println(err)
http.Error(res, "there was an error", http.StatusInternalServerError)
return
}
ps = append(ps, PageData{Id: id})
}
//
if req.Method != "POST" {
adtempl.ExecuteTemplate(res, "delete.html", ps)
return
}
// delete
stmt, err := db.Prepare("delete from new_table where id=?")
if err != nil {
log.Println(err)
http.Error(res, "there was an error", http.StatusInternalServerError)
return
}
rs, err := stmt.Exec(id)
if err != nil {
log.Println(err)
http.Error(res, "there was an error", http.StatusInternalServerError)
return
}
affect, err := rs.RowsAffected()
if err != nil {
log.Println(err)
http.Error(res, "there was an error", http.StatusInternalServerError)
return
}
fmt.Println("row :",affect," affected")
}
func getID(id int64) interface{} {
return id
}
func checkErr(err error) {
if err != nil {
log.Println(err)
}
}
i think the problem should be from line: 138-170.
it's supposed to loop through the db and get the 'is_admin' column and check the value.
if it's 1 then set the cookie to 1 else set it to 2 which means the user on that row can be redirected to user index or admin index.
The session logs into admin whether or not you're admin.
Go is looking harder by the day.
Please I need help. I know my codes are not the best of techniques but you can start from anywhere to help me even if it's about #cleancoding