Example #1
0
// Displays the default home page
func PhotoPOST(w http.ResponseWriter, r *http.Request) {
	// Get session
	sess := session.Instance(r)

	// Get the user photos
	photos, err := model.PhotosByUserId(uint64(sess.Values["id"].(uint32)))
	if err != nil {
		sess.AddFlash(view.Flash{"An error with the server occurred. Please try again later.", view.FlashError})
		sess.Save(r, w)
		Index(w, r)
		return
	}

	// Limit the number of photos
	if len(photos) >= photoLimit {
		sess.AddFlash(view.Flash{"You can only have a max of " + fmt.Sprintf("%v", photoLimit) + " photos. Delete old photos and then try again.", view.FlashError})
		sess.Save(r, w)
		Index(w, r)
		return
	}

	// File upload max size
	if r.ContentLength > 1000000*5 {
		sess.AddFlash(view.Flash{"Photo size is too large. Make sure it is under 5MB.", view.FlashError})
		sess.Save(r, w)
		Index(w, r)
		return
	}

	// Get the form photo
	file, _, err := r.FormFile("photo")

	if err != nil {
		sess.AddFlash(view.Flash{"Photo is missing.", view.FlashError})
		sess.Save(r, w)
		Index(w, r)
		return
	}

	defer file.Close()

	ok, filetype, _ := isSupported(file)

	// Is file supported
	if !ok {
		sess.AddFlash(view.Flash{"Photo type is not supported. Try to upload a JPG, GIF, or PNG.", view.FlashError})
		sess.Save(r, w)
		Index(w, r)
		return
	}

	// Get the photo size
	photo_info, err := photo.ImageDimensions(file)
	if err != nil {
		log.Println(err)
		sess.AddFlash(view.Flash{"Could not read the photo dimensions.", view.FlashError})
		sess.Save(r, w)
		Index(w, r)
		return

	}

	// OKCupid 400 x 400
	// ChristianMingle ?

	if photo_info.Width < 300 || photo_info.Height < 300 {
		sess.AddFlash(view.Flash{"Photo is too small. It must be atleast 300x300 pixels.", view.FlashError})
		sess.Save(r, w)
		Index(w, r)
		return
	}

	user_id := fmt.Sprint(sess.Values["id"])
	folder := photoPath + user_id

	// If folder does not exists
	if !fs.FolderExists(folder) {
		err = os.Mkdir(folder, 0777)
		if err != nil {
			log.Println("Unable to create the folder for writing. Check your write access privilege.", err)
			sess.AddFlash(view.Flash{"An error occurred on the server. Please try again later.", view.FlashError})
			sess.Save(r, w)
			Index(w, r)
			return
		}
	}

	filename := time.Now().Format("20060102150405")

	finalOut := folder + "/" + filename + ".jpg"

	if filetype == "image/gif" {
		img, err := photo.GIFToImage(file)
		if err != nil {
			log.Println(err)
			sess.AddFlash(view.Flash{"An error occurred on the server. Please try again later.", view.FlashError})
			sess.Save(r, w)
			Index(w, r)
			return
		}

		err = photo.ImageToJPGFile(img, finalOut)
	} else if filetype == "image/png" {
		img, err := photo.PNGToImage(file)
		if err != nil {
			log.Println(err)
			sess.AddFlash(view.Flash{"An error occurred on the server. Please try again later.", view.FlashError})
			sess.Save(r, w)
			Index(w, r)
			return
		}
		err = photo.ImageToJPGFile(img, finalOut)
	} else {
		err = photo.JPGToFile(file, finalOut)
	}

	if err != nil {
		log.Println("Error uploading file:", err)
		sess.AddFlash(view.Flash{"An error occurred on the server. Please try again later.", view.FlashError})
	} else {
		uid, err := strconv.ParseUint(user_id, 10, 32)
		if err != nil {
			log.Println(err)
			sess.AddFlash(view.Flash{"An error occurred on the server. Please try again later.", view.FlashError})
			sess.Save(r, w)
			Index(w, r)
			return
		}

		initial := false

		if strings.Contains(r.URL.Path, "initial") {
			initial = true
		}

		err = model.PhotoCreate(uid, filename, initial)
		if err != nil {
			log.Println(err)
			sess.AddFlash(view.Flash{"An error occurred on the server. Please try again later.", view.FlashError})
			sess.Save(r, w)
			Index(w, r)
			return
		}

		err = photo.FixRotation(finalOut)
		if err != nil {
			//log.Println("No rotation:", err, finalOut)
		} else {
			//log.Println("Rotation success", finalOut)
		}

		po, err := pushover.New()
		if err == pushover.ErrPushoverDisabled {
			// Nothing
		} else if err != nil {
			log.Println(err)
		} else {
			err = po.Message("User " + user_id + " added a new photo for verification. You can approve the photo here:\nhttps://verified.ninja/admin/user/" + user_id)
			if err != nil {
				log.Println(err)
			}
		}

		//log.Println("File uploaded successfully:", finalOut)
		sess.AddFlash(view.Flash{"Photo uploaded successfully.", view.FlashSuccess})
	}

	sess.Save(r, w)
	Index(w, r)
	return
}
Example #2
0
func RegisterPOST(w http.ResponseWriter, r *http.Request) {
	// Get session
	sess := session.Instance(r)

	// Prevent brute force login attempts by not hitting MySQL and pretending like it was invalid :-)
	if sess.Values["register_attempt"] != nil && sess.Values["register_attempt"].(int) >= 5 {
		log.Println("Brute force register prevented")
		http.Redirect(w, r, "/register", http.StatusFound)
		return
	}

	// Validate with required fields
	if validate, missingField := view.Validate(r, []string{"first_name", "last_name", "email", "password"}); !validate {
		sess.AddFlash(view.Flash{"Field missing: " + missingField, view.FlashError})
		sess.Save(r, w)
		RegisterGET(w, r)
		return
	}

	// Validate with Google reCAPTCHA
	if !recaptcha.Verified(r) {
		sess.AddFlash(view.Flash{"reCAPTCHA invalid!", view.FlashError})
		sess.Save(r, w)
		RegisterGET(w, r)
		return
	}

	// Get form values
	first_name := r.FormValue("first_name")
	last_name := r.FormValue("last_name")
	email := r.FormValue("email")

	password, errp := passhash.HashString(r.FormValue("password"))

	// If password hashing failed
	if errp != nil {
		log.Println(errp)
		sess.AddFlash(view.Flash{"An error occurred on the server. Please try again later.", view.FlashError})
		sess.Save(r, w)
		http.Redirect(w, r, "/register", http.StatusFound)
		return
	}

	// Get database result
	_, err := model.UserIdByEmail(email)

	if err == sql.ErrNoRows { // If success (no user exists with that email)
		result, ex := model.UserCreate(first_name, last_name, email, password)
		// Will only error if there is a problem with the query
		if ex != nil {
			log.Println(ex)
			sess.AddFlash(view.Flash{"An error occurred on the server. Please try again later.", view.FlashError})
			sess.Save(r, w)
		} else {

			// Create the email verification string
			md := random.Generate(32)

			// Get the user ID
			user_id, _ := result.LastInsertId()

			// Add the user role
			model.RoleCreate(user_id, model.Role_level_User)

			// Add the hash to the database
			model.UserEmailVerificationCreate(user_id, md)

			c := view.ReadConfig()

			// Email the hash to the user
			err := emailer.SendEmail(email, "Email Verification for Verified.ninja", "Hi "+first_name+",\n\nTo verify your email address, please click here: "+c.BaseURI+"emailverification/"+md)
			if err != nil {
				log.Println(err)
			}

			// TODO This is just temporary for testing
			log.Println("Email Verification Link:", c.BaseURI+"emailverification/"+md)

			po, err := pushover.New()
			if err == pushover.ErrPushoverDisabled {
				// Nothing
			} else if err != nil {
				log.Println(err)
			} else {
				err = po.Message(first_name + " " + last_name + "(" + fmt.Sprintf("%v", user_id) + ") created an account. You can view the account here:\nhttps://verified.ninja/admin/user/" + fmt.Sprintf("%v", user_id))
				if err != nil {
					log.Println(err)
				}
			}

			sess.AddFlash(view.Flash{"Account created successfully for: " + email + ". Please click the verification link in your email.", view.FlashSuccess})
			sess.Save(r, w)
			http.Redirect(w, r, "/login", http.StatusFound)
			return
		}
	} else if err != nil { // Catch all other errors
		log.Println(err)
		sess.AddFlash(view.Flash{"An error occurred on the server. Please try again later.", view.FlashError})
		sess.Save(r, w)
	} else { // Else the user already exists
		sess.AddFlash(view.Flash{"Account already exists for: " + email, view.FlashError})
		sess.Save(r, w)
	}

	// Display the page
	RegisterGET(w, r)
}