Skip to content

Instantly share code, notes, and snippets.

View lettergram's full-sized avatar
🕶️
Loading...

Austin Walters lettergram

🕶️
Loading...
View GitHub Profile
import (
"fmt"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
)
type Book struct {
Title string
Author string
ISBN string
Genre string
Id string
}
// Creates an account and adds it to the Database
// Finds book already in database
func FindBook(bookid string) (book *Book) {
session, err := mgo.Dial("127.0.0.1:27017/")
if err != nil {
fmt.Println(err)
return nil
}
// Opens the "library" databases, "books" collection
// Adds a new book to the book database and user
func bookHandler(w http.ResponseWriter, r *http.Request) {
// Parses username from the cookie
cookie, _ := r.Cookie("SessionID")
sessionID := cookie.Value
z := strings.Split(sessionID, ":")
username := z[0]
// Checks to see if user exists
for i := 0; i < 5; i++ {
if i < len(userProfile.BookList) {
book := bkz.FindBook(userProfile.BookList[i])
link := "<a href='books/" + book.ISBN + ".info'>"
str += link + book.Title + "</a><br><br>"
} else {
str += "<a href='/add-book'>Add Book!</a><br><br>"
}
}
func LoginCookie(username string) http.Cookie {
cookieValue := username + ":" + codify.SHA(username+strconv.Itoa(rand.Intn(100000000)))
expire := time.Now().AddDate(0, 0, 1)
return http.Cookie{Name: "SessionID", Value: cookieValue, Expires: expire, HttpOnly: true}
}
// Check if the user is logged in, true if they do
func IsLoggedIn(r *http.Request) bool {
// Obtains cookie from users http.Request
cookie, err := r.Cookie("SessionID")
if err != nil {
fmt.Println(err)
return false
}
// Shows user requested page
func viewHandler(w http.ResponseWriter, r *http.Request) {
// Parses URL to obtain title of file to add to .body
title := r.URL.Path[len("/"):]
// Load templatized page, given title
p, err := loadPage(title, r)
// If they do not have a cookie force them to login
<form>
Email: <input type="text" name="email"><br>
Password: <input type="password" name="pwd"><br>
<input type="submit" value="Submit">
</form>
// Handles the users login and gives them a cookie for doing so
func loginHandler(w http.ResponseWriter, r *http.Request) {
// Generate a new User Struct
usr := new(user.User)
// Read the email value from the form
usr.Email = r.FormValue("email")
// Read the password value from the form