func EmailVerificationGET(w http.ResponseWriter, r *http.Request) { // Get session sess := session.Instance(r) var params httprouter.Params params = context.Get(r, "params").(httprouter.Params) token := params.ByName("token") result, err := model.UserEmailVerified(token) // Will only error if there is a problem with the query if err != nil { //log.Println(err) sess.AddFlash(view.Flash{"Email verification link is not valid. Please check the latest email we sent you.", view.FlashError}) sess.Save(r, w) } else if result { sess.AddFlash(view.Flash{"Email verified. You may login now.", view.FlashSuccess}) sess.Save(r, w) } else { sess.AddFlash(view.Flash{"An error occurred on the server. Please try again later.", view.FlashError}) sess.Save(r, w) } http.Redirect(w, r, "/", http.StatusFound) }
func deletePhoto(w http.ResponseWriter, r *http.Request) { // Get session sess := session.Instance(r) var params httprouter.Params params = context.Get(r, "params").(httprouter.Params) //userid := params.ByName("userid") //userid := uint64(site_idInt) userid := uint64(sess.Values["id"].(uint32)) picid := params.ByName("picid") err := model.PhotoDelete(userid, picid) 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) } else { /*err = os.Remove(photoPath + fmt.Sprintf("%v", userid) + "/" + picid + ".jpg") if err != nil { log.Println(err) }*/ sess.AddFlash(view.Flash{"Photo removed!", view.FlashSuccess}) sess.Save(r, w) } }
// Displays the default home page func Index(w http.ResponseWriter, r *http.Request) { // Get session sess := session.Instance(r) // If the user is logged in if sess.Values["id"] != nil { // Get the current user role currentUID, _ := CurrentUserId(r) role, err := model.RoleByUserId(int64(currentUID)) if err != nil { log.Println(err) Error500(w, r) return } if role.Level_id == model.Role_level_User { http.Redirect(w, r, "/profile", http.StatusFound) return } else { http.Redirect(w, r, "/admin", http.StatusFound) return } } else { // Display the view v := view.New(r) v.Name = "anon_home" v.Render(w) } }
// New returns a new view func New(req *http.Request) *View { v := &View{} v.Vars = make(map[string]interface{}) v.Vars["AuthLevel"] = "anon" v.BaseURI = viewInfo.BaseURI v.Extension = viewInfo.Extension v.Folder = viewInfo.Folder v.Name = viewInfo.Name // Make sure BaseURI is available in the templates v.Vars["BaseURI"] = v.BaseURI // This is required for the view to access the request v.request = req // Get session session := session.Instance(v.request) // Set the AuthLevel to auth if the user is logged in if session.Values["id"] != nil { v.Vars["AuthLevel"] = "auth" v.Vars["UserFirstName"] = session.Values["first_name"] v.Vars["UserIdGA"] = session.Values["id"] } else { v.Vars["UserIdGA"] = 0 } return v }
func PhotoUploadGET(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 { log.Println(err) } verified := false for _, v := range photos { if v.Status_id == 1 { verified = true break } } // Only allow access to this page if verified if verified { // Display the view v := view.New(r) v.Name = "user_upload" v.Render(w) } else { Error404(w, r) } }
func PhotoDownloadGET(w http.ResponseWriter, r *http.Request) { // Get session sess := session.Instance(r) var params = context.Get(r, "params").(httprouter.Params) //userid := params.ByName("userid") pic_id := params.ByName("picid") //user_id, _ := strconv.Atoi(userid) user_id := uint64(sess.Values["id"].(uint32)) userid := strconv.Itoa(int(user_id)) if allowed, mark, err := photoAccessAllowed(r, user_id, pic_id); allowed { buffer, err := renderImage(w, r, userid, pic_id, mark) if err != nil { log.Println(err) Error500(w, r) return } // Force download w.Header().Set("Content-Disposition", `attachment; filename="`+pic_id+`"`) w.Header().Set("Content-Type", r.Header.Get("Content-Type")) http.ServeContent(w, r, pic_id, time.Now(), bytes.NewReader(buffer.Bytes())) } else if err != sql.ErrNoRows { log.Println(err) Error500(w, r) return } else { //log.Println("User does not have access to the photo.") Error401(w, r) return } }
// Returns the user_id in uint32 and whether the a user is logged in func CurrentUserId(r *http.Request) (uint32, bool) { // Get session sess := session.Instance(r) if sess.Values["id"] == nil { return 0, false } return sess.Values["id"].(uint32), true }
func ContactPOST(w http.ResponseWriter, r *http.Request) { // Get session sess := session.Instance(r) // Validate with required fields if validate, missingField := view.Validate(r, []string{"email", "fullname", "message"}); !validate { sess.AddFlash(view.Flash{"Field missing: " + missingField, view.FlashError}) sess.Save(r, w) ContactGET(w, r) return } // Validate with Google reCAPTCHA if !recaptcha.Verified(r) { sess.AddFlash(view.Flash{"reCAPTCHA invalid!", view.FlashError}) sess.Save(r, w) ContactGET(w, r) return } // Form values email := r.FormValue("email") name := r.FormValue("fullname") message := r.FormValue("message") ip, err := model.GetRemoteIP(r) if err != nil { log.Println(err) } user := "******" if sess.Values["id"] != nil { user = fmt.Sprintf("Registered (%v)", sess.Values["id"]) } // Email the hash to the user err = emailer.SendEmail(emailer.ReadConfig().From, "Contact Submission for Verified.ninja", "From: "+ name+" <"+email+">\nUser: "******"\nIP: "+ip+"\nMessage: "+message) 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) ContactGET(w, r) return } // Post successful sess.AddFlash(view.Flash{"Thanks for the message! We'll get back to you in a bit.", view.FlashSuccess}) sess.Save(r, w) http.Redirect(w, r, "/", http.StatusFound) return }
func Logout(w http.ResponseWriter, r *http.Request) { // Get session sess := session.Instance(r) // If user is authenticated if sess.Values["id"] != nil { clearSessionVariables(sess) sess.AddFlash(view.Flash{"Goodbye!", view.FlashNotice}) sess.Save(r, w) } http.Redirect(w, r, "/", http.StatusFound) }
// DisallowAnon does not allow anonymous users to access the page func DisallowAnon(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Get session sess := session.Instance(r) // If user is not authenticated, don't allow them to access the page if sess.Values["id"] == nil { http.Redirect(w, r, "/", http.StatusFound) return } h.ServeHTTP(w, r) }) }
func UserSiteGET(w http.ResponseWriter, r *http.Request) { // Get session sess := session.Instance(r) // Does the user have a verified photo verified := isVerified(r) // Only allow access to this page if verified if verified { // Get database result sites, err := model.SiteList() if err != nil { log.Println(err) Error500(w, r) return } user_id := uint64(sess.Values["id"].(uint32)) usernames, err := model.UsernamesByUserId(user_id) if err != nil { log.Println(err) Error500(w, r) return } // err == sql.ErrNoRows // Display the view v := view.New(r) v.Name = "user_site" v.Vars["first_name"] = sess.Values["first_name"] v.Vars["sites"] = sites // Copy the usernames into a map so they can be used in the form inputs data := make(map[uint32]string) for _, u := range usernames { data[u.Site_id] = u.Name } v.Vars["data"] = data v.Render(w) } else { Error404(w, r) } }
func APIRegisterChromeGET(w http.ResponseWriter, r *http.Request) { // Get session sess := session.Instance(r) // If the user is logged in if sess.Values["id"] == nil { w.Header().Set("Content-Type", "application/json") w.Write([]byte(`{"error": "Authentication required"}`)) return } user_id := uint64(sess.Values["id"].(uint32)) ci := ChromeInfo{} auth, err := model.ApiAuthenticationByUserId(user_id) // If there is no record yet, create one if err == sql.ErrNoRows { // Create values ci.Userkey = random.Generate(32) ci.Token = random.Generate(32) err := model.ApiAuthenticationCreate(user_id, ci.Userkey, ci.Token) if err != nil { log.Println(err) Error500(w, r) return } } else if err != nil { log.Println(err) Error500(w, r) return } else { ci.Userkey = auth.Userkey ci.Token = auth.Token } js, err := json.Marshal(ci) if err != nil { log.Println(err) Error500(w, r) return } w.Header().Set("Content-Type", "application/json") w.Write(js) }
func (v *View) SendFlashes(w http.ResponseWriter) { // Get session sess := session.Instance(v.request) flashes := peekFlashes(w, v.request) sess.Save(v.request, w) js, err := json.Marshal(flashes) if err != nil { http.Error(w, "JSON Error: "+err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.Write(js) }
func isVerified(r *http.Request) bool { // Get session sess := session.Instance(r) // Get the user photos photos, err := model.PhotosByUserId(uint64(sess.Values["id"].(uint32))) if err != nil { log.Println(err) } verified := false for _, v := range photos { if v.Status_id == 1 { verified = true break } } return verified }
func UserEmailGET(w http.ResponseWriter, r *http.Request) { // Get session sess := session.Instance(r) user_id := int64(sess.Values["id"].(uint32)) if !isVerifiedEmail(r, user_id) { sess.AddFlash(view.Flash{"You can't change you email again until you verify your current email.", view.FlashError}) sess.Save(r, w) http.Redirect(w, r, "/", http.StatusFound) } // Display the view v := view.New(r) v.Name = "user_email" v.Vars["emailold"] = sess.Values["email"] // Refill any form fields view.Repopulate([]string{"email"}, r.Form, v.Vars) v.Render(w) }
func AdminRejectGET(w http.ResponseWriter, r *http.Request) { // Get session sess := session.Instance(r) var params httprouter.Params params = context.Get(r, "params").(httprouter.Params) userid := params.ByName("userid") picid := params.ByName("picid") note := r.FormValue("note") uid, _ := strconv.Atoi(userid) err := model.PhotoReject(picid, uint64(uid), note) 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) } else { sess.AddFlash(view.Flash{"Photo rejected!", view.FlashSuccess}) sess.Save(r, w) user_info, err := model.UserEmailByUserId(int64(uid)) if err != nil { log.Println() } else { c := view.ReadConfig() // Email the update to the user err := emailer.SendEmail(user_info.Email, "Photo Rejected on Verified.ninja", "Hi "+user_info.First_name+",\n\nYour photo ("+picid+") was rejected for the following reason(s):\n"+note+"\n\nPlease upload a new private photo for verification: "+c.BaseURI) if err != nil { log.Println(err) } } } // Display the view v := view.New(r) v.SendFlashes(w) }
func UserInformationGET(w http.ResponseWriter, r *http.Request) { // Get session sess := session.Instance(r) user_id := uint64(sess.Values["id"].(uint32)) demo, err := model.DemographicByUserId(user_id) if err != nil && err != sql.ErrNoRows { log.Println(err) } ethnicity, err := model.EthnicityByUserId(user_id) if err != nil && err != sql.ErrNoRows { log.Println(err) } e := make(map[string]int) for i := 0; i <= 9; i++ { ee := fmt.Sprintf("%v", i) e["E"+ee] = 0 for j := 0; j < len(ethnicity); j++ { if int(ethnicity[j].Type_id) == i { e["E"+ee] = 1 } } } // Display the view v := view.New(r) v.Name = "user_info" //v.Vars["token"] = csrfbanana.Token(w, r, sess) v.Vars["first_name"] = sess.Values["first_name"] v.Vars["demographic"] = demo v.Vars["ethnicity"] = e v.Render(w) }
func ContactGET(w http.ResponseWriter, r *http.Request) { // Get session sess := session.Instance(r) // Display the view v := view.New(r) v.Name = "contact" // If the user is logged in if sess.Values["id"] != nil { // Refill any form fields view.Repopulate([]string{"message"}, r.Form, v.Vars) v.Vars["email"] = sess.Values["email"] v.Vars["fullname"] = fmt.Sprintf("%v %v", sess.Values["first_name"], sess.Values["last_name"]) v.Vars["logged_in"] = true } else { // Refill any form fields view.Repopulate([]string{"email", "fullname", "message"}, r.Form, v.Vars) } v.Render(w) }
func peekFlashes(w http.ResponseWriter, r *http.Request) []Flash { // Get session sess := session.Instance(r) v := make([]Flash, 0) // Get the flashes for the template if flashes := sess.Flashes(); len(flashes) > 0 { v = make([]Flash, len(flashes)) for i, f := range flashes { switch f.(type) { case Flash: v[i] = f.(Flash) default: v[i] = Flash{f.(string), "alert-box"} } } } return v }
func AdminApproveGET(w http.ResponseWriter, r *http.Request) { // Get session sess := session.Instance(r) var params httprouter.Params params = context.Get(r, "params").(httprouter.Params) userid := params.ByName("userid") picid := params.ByName("picid") uid, _ := strconv.Atoi(userid) err := model.PhotoApprove(picid, uint64(uid)) 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) } else { sess.AddFlash(view.Flash{"Photo approved!", view.FlashSuccess}) sess.Save(r, w) user_info, err := model.UserEmailByUserId(int64(uid)) if err != nil { log.Println() } else { c := view.ReadConfig() // Email the update to the user err := emailer.SendEmail(user_info.Email, "Photo Approved on Verified.ninja", "Hi "+user_info.First_name+",\n\nYour photo ("+picid+") was approved!\n\nLogin to see your updated profile: "+c.BaseURI) if err != nil { log.Println(err) } } } // Display the view v := view.New(r) v.SendFlashes(w) }
// Handler will log the HTTP requests func Database(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if !strings.Contains(r.URL.Path, "/api/v1/verify") { // Get session sess := session.Instance(r) user_id := uint64(0) // If the user is logged in if sess.Values["id"] != nil { user_id = uint64(sess.Values["id"].(uint32)) } err := model.TrackRequestURL(user_id, r) if err != nil { log.Println(err) } } next.ServeHTTP(w, r) }) }
func AdminUnverifyGET(w http.ResponseWriter, r *http.Request) { // Get session sess := session.Instance(r) var params httprouter.Params params = context.Get(r, "params").(httprouter.Params) userid := params.ByName("userid") picid := params.ByName("picid") uid, _ := strconv.Atoi(userid) err := model.PhotoUnverify(picid, uint64(uid)) 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) } else { sess.AddFlash(view.Flash{"Photo unverified!", view.FlashSuccess}) sess.Save(r, w) } // Display the view v := view.New(r) v.SendFlashes(w) }
// 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 }
func UserSitePOST(w http.ResponseWriter, r *http.Request) { // Get session sess := session.Instance(r) // Does the user have a verified photo verified := isVerified(r) // Only allow access to this page if verified if verified { err := r.ParseForm() if err != nil { log.Println(err) return } user_id := uint64(sess.Values["id"].(uint32)) for site_id, values := range r.Form { site_idInt, err := strconv.Atoi(site_id) if err != nil { log.Println(err) continue } if len(values) < 1 { log.Println("Value is missing!", site_id) continue } username := values[0] if len(strings.TrimSpace(username)) < 1 { result, err := model.UsernameRemove(user_id, uint64(site_idInt)) if err != nil { log.Println(err) sess.AddFlash(view.Flash{"There was an issue with the username: "******". Please try again later.", view.FlashError}) sess.Save(r, w) } else { affected, err := result.RowsAffected() if err != nil { log.Println(err) } else if affected > 0 { sess.AddFlash(view.Flash{"Removed username", view.FlashSuccess}) sess.Save(r, w) } } } else { err = model.UsernameAdd(user_id, username, uint64(site_idInt)) if err != nil { log.Println(err) sess.AddFlash(view.Flash{"There was an issue with the username: "******". Please try again later.", view.FlashError}) sess.Save(r, w) } else { sess.AddFlash(view.Flash{"Saved username: "******"/profile", http.StatusFound) } else { Error404(w, r) } }
func InitialPhotoGET(w http.ResponseWriter, r *http.Request) { // Get session sess := session.Instance(r) user_id := uint64(sess.Values["id"].(uint32)) demo, err := model.DemographicByUserId(user_id) if err != sql.ErrNoRows { //log.Println(err) } // Force the user to enter in demographic information if len(demo.Gender) < 1 { UserInformationGET(w, r) return } // If the user has no photos, show this page // If the user has only unverified photos, show the waiting screen // Get the user photos photos, err := model.PhotosByUserId(uint64(sess.Values["id"].(uint32))) if err != nil { log.Println(err) } verified_private := false unverified_private := false //rejected_private := false any_private := false for _, v := range photos { if v.Initial == 1 { if v.Status_id == 1 { verified_private = true } else if v.Status_id == 2 { unverified_private = true } else if v.Status_id == 3 { //rejected_private = true } any_private = true } } // Redirect to profile to handle caess where all private photos are rejected if len(photos) < 1 || verified_private || !any_private { // Get the user verification code token_info, err := model.UserTokenByUserId(user_id) if err == sql.ErrNoRows { token_info.Token = random.Generate(6) token_info.User_id = uint32(user_id) err = model.UserTokenCreate(user_id, token_info.Token) } else if err != nil { log.Println(err) Error500(w, r) return } // Display the view v := view.New(r) v.Name = "user_step1" v.Vars["user_token"] = token_info.Token v.Vars["first_name"] = sess.Values["first_name"] v.Render(w) } else if unverified_private { http.Redirect(w, r, "/profile", http.StatusFound) } else { //Error404(w, r) http.Redirect(w, r, "/profile", http.StatusFound) } }
func UserProfileGET(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 { log.Println(err) } note := "" photo := "" status := uint8(0) date := time.Now() verified_private := false unverified_private := false rejected_private := false verified_public := false for _, v := range photos { if v.Initial == 1 { if v.Status_id == 1 { verified_private = true } else if v.Status_id == 2 { unverified_private = true note = v.Note photo = v.Path status = v.Status_id date = v.Updated_at } else if v.Status_id == 3 { rejected_private = true note = v.Note photo = v.Path status = v.Status_id date = v.Updated_at } } else { if v.Status_id == 1 { verified_public = true } } } user_id := strconv.Itoa(int(sess.Values["id"].(uint32))) // Display the view v := view.New(r) v.Vars["isNinja"] = false // If a private photo is verified, show the page if verified_private { v.Name = "user_profile" // Get the photo information imagesDB, err := model.PhotosByUserId(uint64(sess.Values["id"].(uint32))) if err != nil { log.Println(err) return } images := []Image{} for _, val := range imagesDB { img := Image{} img.Name = val.Path /*if val.Status_id == 1 { img.Path = "image/" + user_id + "/" + val.Path + ".jpg" } else { img.Path = photoPath + user_id + "/" + val.Path + ".jpg" }*/ img.Path = "image/" + user_id + "/" + val.Path + ".jpg" img.Status_id = int(val.Status_id) img.Date = val.Updated_at.Format("Jan _2, 2006") img.Initial = int(val.Initial) img.Note = val.Note images = append(images, img) } v.Vars["images"] = images // Get the username information sites, err := model.UserinfoByUserId(uint64(sess.Values["id"].(uint32))) if err != nil { log.Println(err) return } for i, val := range sites { sites[i].Profile = strings.Replace(val.Profile, ":name", val.Username, -1) } v.Vars["sites"] = sites if len(sites) > 0 && verified_public { v.Vars["isNinja"] = true } } else { if unverified_private { // THIS NOTE MAY NOT BE FOR THE CORRECT PICTURE v.Vars["note"] = note //v.Vars["photo"] = photoPath + user_id + "/" + photo + ".jpg" v.Vars["photo"] = "image/" + user_id + "/" + photo + ".jpg" v.Vars["status_id"] = status v.Vars["date"] = date.Format("Jan _2, 2006") v.Vars["photo_id"] = photo v.Name = "user_unverified" } else if rejected_private { // THIS NOTE MAY NOT BE FOR THE CORRECT PICTURE v.Vars["note"] = note //v.Vars["photo"] = photoPath + user_id + "/" + photo + ".jpg" v.Vars["photo"] = "image/" + user_id + "/" + photo + ".jpg" v.Vars["status_id"] = status v.Vars["date"] = date.Format("Jan _2, 2006") v.Vars["photo_id"] = photo v.Name = "user_rejected" } else { http.Redirect(w, r, "/profile/initial", http.StatusFound) return } } v.Vars["first_name"] = sess.Values["first_name"] v.Render(w) }
func UserInformationPOST(w http.ResponseWriter, r *http.Request) { // Get session sess := session.Instance(r) // Validate with required fields if validate, missingField := view.Validate(r, []string{"birth_month", "birth_day", "birth_year", "gender", "height_feet", "height_inches", "ethnicity"}); !validate { sess.AddFlash(view.Flash{"Field missing: " + missingField, view.FlashError}) sess.Save(r, w) UserInformationGET(w, r) return } user_id := uint64(sess.Values["id"].(uint32)) d := model.Demographic{} // Get form values bm, err := strconv.Atoi(r.FormValue("birth_month")) 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) UserInformationGET(w, r) return } bd, _ := strconv.Atoi(r.FormValue("birth_day")) 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) UserInformationGET(w, r) return } by, _ := strconv.Atoi(r.FormValue("birth_year")) 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) UserInformationGET(w, r) return } d.Birth_month = uint8(bm) d.Birth_day = uint8(bd) d.Birth_year = uint16(by) d.Gender = r.FormValue("gender") hf, _ := strconv.Atoi(r.FormValue("height_feet")) 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) UserInformationGET(w, r) return } d.Height_feet = uint8(hf) hi, _ := strconv.Atoi(r.FormValue("height_inches")) 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) UserInformationGET(w, r) return } d.Height_inches = uint8(hi) we, _ := strconv.Atoi(r.FormValue("weight")) 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) UserInformationGET(w, r) return } d.Weight = uint16(we) err = model.DemographicAdd(user_id, d) 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) UserInformationGET(w, r) return } err = model.EthnicityAdd(user_id, r.Form["ethnicity"]) 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) UserInformationGET(w, r) return } sess.AddFlash(view.Flash{"Settings saved.", view.FlashSuccess}) sess.Save(r, w) http.Redirect(w, r, "/", http.StatusFound) }
func UserEmailPOST(w http.ResponseWriter, r *http.Request) { // Get session sess := session.Instance(r) user_id := int64(sess.Values["id"].(uint32)) if !isVerifiedEmail(r, user_id) { sess.AddFlash(view.Flash{"You can't change you email again until you verify your current email.", view.FlashError}) sess.Save(r, w) http.Redirect(w, r, "/", http.StatusFound) } // Validate with required fields if validate, missingField := view.Validate(r, []string{"email"}); !validate { sess.AddFlash(view.Flash{"Field missing: " + missingField, view.FlashError}) sess.Save(r, w) UserEmailGET(w, r) return } // Validate with Google reCAPTCHA if !recaptcha.Verified(r) { sess.AddFlash(view.Flash{"reCAPTCHA invalid!", view.FlashError}) sess.Save(r, w) UserEmailGET(w, r) return } // Form values email := r.FormValue("email") emailOld := sess.Values["email"] if email == emailOld { sess.AddFlash(view.Flash{"New email cannot be the same as the old email.", view.FlashError}) sess.Save(r, w) UserEmailGET(w, r) return } // Get database result err := model.UserEmailUpdate(user_id, email) if err != nil { if strings.Contains(err.Error(), "Duplicate entry") { sess.AddFlash(view.Flash{"That email already exists in the database. Please use a different one.", view.FlashError}) } else { // Display error message log.Println(err) sess.AddFlash(view.Flash{"There was an error. Please try again later.", view.FlashError}) } sess.Save(r, w) UserEmailGET(w, r) return } first_name := fmt.Sprintf("%v", sess.Values["first_name"]) // Create the email verification string md := random.Generate(32) // Add the hash to the database err = model.UserEmailVerificationCreate(user_id, md) if err != nil { log.Println(err) } err = model.UserReverify(user_id) if err != nil { log.Println(err) } 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 ("+email+"), please click here: "+c.BaseURI+"emailverification/"+md) if err != nil { log.Println(err) } // Login successfully sess.AddFlash(view.Flash{"Email updated! You must verify your email before you can login again.", view.FlashSuccess}) sess.Values["email"] = email sess.Save(r, w) http.Redirect(w, r, "/", http.StatusFound) }
// Render a template to the screen func (v *View) Render(w http.ResponseWriter) { // Get the template collection from cache mutex.RLock() tc, ok := templateCollection[v.Name] mutex.RUnlock() // Get the plugin collection mutexPlugins.RLock() pc := pluginCollection mutexPlugins.RUnlock() // If the template collection is not cached or caching is disabled if !ok || !viewInfo.Caching { // List of template names templateList := make([]string, 0) templateList = append(templateList, rootTemplate) templateList = append(templateList, v.Name) templateList = append(templateList, childTemplates...) // Loop through each template and test the full path for i, name := range templateList { // Get the absolute path of the root template path, err := filepath.Abs(v.Folder + string(os.PathSeparator) + name + "." + v.Extension) if err != nil { http.Error(w, "Template Path Error: "+err.Error(), http.StatusInternalServerError) return } templateList[i] = path } // Determine if there is an error in the template syntax templates, err := template.New(v.Name).Funcs(pc).ParseFiles(templateList...) if err != nil { http.Error(w, "Template Parse Error: "+err.Error(), http.StatusInternalServerError) return } // Cache the template collection mutex.Lock() templateCollection[v.Name] = templates mutex.Unlock() // Save the template collection tc = templates } // Get session sess := session.Instance(v.request) // Get the flashes for the template if flashes := sess.Flashes(); len(flashes) > 0 { v.Vars["flashes"] = make([]Flash, len(flashes)) for i, f := range flashes { switch f.(type) { case Flash: v.Vars["flashes"].([]Flash)[i] = f.(Flash) default: v.Vars["flashes"].([]Flash)[i] = Flash{f.(string), "alert-box"} } } sess.Save(v.request, w) } // Display the content to the screen err := tc.Funcs(pc).ExecuteTemplate(w, rootTemplate+"."+v.Extension, v.Vars) if err != nil { http.Error(w, "Template File Error: "+err.Error(), http.StatusInternalServerError) } }
func UserPasswordPOST(w http.ResponseWriter, r *http.Request) { // Get session sess := session.Instance(r) // Validate with required fields if validate, missingField := view.Validate(r, []string{"passwordold", "passwordnew"}); !validate { sess.AddFlash(view.Flash{"Field missing: " + missingField, view.FlashError}) sess.Save(r, w) UserPasswordGET(w, r) return } user_id := int64(sess.Values["id"].(uint32)) // Form values passwordOld := r.FormValue("passwordold") passwordNew, errp := passhash.HashString(r.FormValue("passwordnew")) if passwordOld == r.FormValue("passwordnew") { sess.AddFlash(view.Flash{"New password cannot be the same as the old password.", view.FlashError}) sess.Save(r, w) UserPasswordGET(w, r) return } // 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) UserPasswordGET(w, r) return } // Get database result result, err := model.UserByEmail(fmt.Sprintf("%v", sess.Values["email"])) // Determine if user exists if err == sql.ErrNoRows { sess.AddFlash(view.Flash{"Password is incorrect.", view.FlashWarning}) sess.Save(r, w) UserPasswordGET(w, r) return } else if err != nil { // Display error message log.Println(err) sess.AddFlash(view.Flash{"There was an error. Please try again later.", view.FlashError}) sess.Save(r, w) UserPasswordGET(w, r) return } else if passhash.MatchString(result.Password, passwordOld) { err = model.UserPasswordUpdate(user_id, passwordNew) if err != nil { log.Println(err) sess.AddFlash(view.Flash{"There was an error. Please try again later.", view.FlashError}) sess.Save(r, w) UserPasswordGET(w, r) return } // Password matches sess.AddFlash(view.Flash{"Password changed!", view.FlashSuccess}) sess.Save(r, w) http.Redirect(w, r, "/", http.StatusFound) return } else { sess.AddFlash(view.Flash{"Password is incorrect.", view.FlashWarning}) sess.Save(r, w) UserPasswordGET(w, r) return } }