func Login(session sessions.Session, su models.User, r render.Render, p *models.Page) { // Check if we are already logged in if su.Id > 0 { r.Redirect(strings.Join([]string{utils.AppCfg.Url(), "albums"}, "/"), http.StatusFound) return } session.Set("loggedin", "false") // Init error holder errs := make(map[string]string) err_flash := session.Get("flash") if err_flash != nil { errs["flash"] = err_flash.(string) session.Set("flash", nil) } genform := utils.GenerateForm(&forms.Login{}, "/login", "POST", errs) p.SetUser(su) p.SetTitle("Login") p.Data = LoginVars{Form: genform} encoder.Render(p.Encoding, 200, "login", p, r) }
func Login(session sessions.Session, re render.Render, r *http.Request) { client_id := common.Config.OAuth2Client_ID letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") b := make([]rune, 10) for i := range b { b[i] = letters[rand.Intn(len(letters))] } session.AddFlash(string(b), "state") redirectBack := r.URL.Query().Get("redirect_back") ref := r.Referer() if redirectBack == "true" && ref != "" { session.Set("redirect_to", ref) } else { session.Set("redirect_to", nil) } query := url.Values{} query.Set("client_id", client_id) query.Set("state", string(b)) query.Set("scope", "repo") dest := url.URL{ Scheme: "https", Host: "github.com", Path: "/login/oauth/authorize", RawQuery: query.Encode(), } re.Redirect(dest.String()) }
func getLoginPage(user sessionauth.User, r render.Render) { if user.IsAuthenticated() { r.Redirect(INDEX_PAGE) return } r.HTML(200, LOGIN_PAGE, nil) }
func UpdatePlant(ren render.Render, mediaManager *media.Manager, r *http.Request, db *sql.DB, params martini.Params, sessionMessages *template.Messages) { id, _ := strconv.ParseInt(params["id"], 10, 64) plant := entity.NewPlant() plant.Populate(getPlantMap(r, params["id"])) val, errors := validation.ValidateDefaultEntity(plant, db, PLANT) if val { _, err := repository.UpdatePlant(plant, db, params["id"]) if err != nil { log.Println(err) sessionMessages.AddDanger("Failed to update plant.") } else { sessionMessages.AddSuccess("Successfully update plant.") updatePopularNames(db, id, PLANT, plant.GetPopularNames().GetValues()) createMedia(r, mediaManager, db, sessionMessages, PLANT, id) } ren.Redirect("/plant/") } else { for k, msg := range errors { sessionMessages.AddDanger(k + ": " + msg) } ren.Redirect("/plant/" + params["id"]) } }
func upload_battle(w http.ResponseWriter, r *http.Request, out render.Render) { file, _, err := r.FormFile("txtUpload") if err != nil { fmt.Fprintln(w, err) return } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { str := scanner.Text() //fmt.Println(str) beg := strings.Index(str, "\"") end := strings.LastIndex(str, "\"") if beg != -1 && end != -1 { jsonString := strings.Replace(str[beg+1:end], "\\\"", "\"", -1) saveBattle(jsonString) } } if err = scanner.Err(); err != nil { //fmt.Fprintln(w, err) fmt.Println(err) } out.Redirect("/") }
func Random(db model.Model, r render.Render, req *http.Request, isJson IsJson) { qs := req.URL.Query() search := qs.Get("query") maxLines, err := strconv.Atoi(qs.Get("max-lines")) if err != nil || maxLines < 1 { maxLines = 0 } quotes, err := db.GetQuotes(model.Query{ Limit: 1, Search: search, MaxLines: maxLines, OrderBy: []string{"rand()"}, IncludeTags: qs["tags"], ExcludeTags: qs["exclude-tags"], }) if err != nil || len(quotes) == 0 { RenderError(r, 500, isJson, fmt.Sprint("quote not found", err)) return } quote := quotes[0] if isJson { r.JSON(200, quote) } else { r.Redirect(fmt.Sprintf("/quote/%d", quote.ID)) } }
func EditPlant(ren render.Render, db *sql.DB, params martini.Params, t *template.TemplateData) { var plant_id string = params["id"] if plant_id != "new" { plant, err := repository.GetPlant(db, plant_id) if err != nil || plant == nil { t.SessionMessage.AddDanger("Failed to load plant.") ren.Redirect("/plant") return } id, _ := strconv.ParseInt(params["id"], 10, 64) plant.PopularNames.Names, err = repository.GetPopularNames(db, id, PLANT) t.Data = plant t.MediaList = getMediaList(db, PLANT, id) ren.HTML(200, "blah/plant/edit", t) } else { ren.HTML(200, "blah/plant/edit", nil) } }
func CreateInvertebrate(ren render.Render, mediaManager *media.Manager, r *http.Request, db *sql.DB, params martini.Params, sessionMessages *template.Messages) { invertebrate := entity.NewInvertebrate() invertebrate.Populate(getInvertebrateMap(r, "")) val, errors := validation.ValidateDefaultEntity(invertebrate, db, INVERTEBRATE) if val { res, err := repository.InsertInvertebrate(invertebrate, db) if err != nil { log.Println(err) sessionMessages.AddDanger("Failed to create invertebrate.") } else { sessionMessages.AddSuccess("Successfully created invertebrate.") id, _ := res.LastInsertId() insertPopularNames(db, id, INVERTEBRATE, invertebrate.GetPopularNames().GetValues()) createMedia(r, mediaManager, db, sessionMessages, INVERTEBRATE, id) } ren.Redirect("/invertebrate") } else { for k, msg := range errors { sessionMessages.AddDanger(k + ": " + msg) } ren.Redirect("/invertebrate/new") } }
func UpdateInvertebrate(ren render.Render, mediaManager *media.Manager, r *http.Request, db *sql.DB, params martini.Params, sessionMessages *template.Messages) { id, _ := strconv.ParseInt(params["id"], 10, 64) invertebrate := entity.NewInvertebrate() invertebrate.Populate(getInvertebrateMap(r, params["id"])) val, errors := validation.ValidateDefaultEntity(invertebrate, db, INVERTEBRATE) if val { _, err := repository.UpdateInvertebrate(invertebrate, db, params["id"]) if err != nil { log.Println(err) sessionMessages.AddDanger("Failed to upload invertebrate.") } else { sessionMessages.AddSuccess("Successfully upload invertebrate.") updatePopularNames(db, id, INVERTEBRATE, invertebrate.GetPopularNames().GetValues()) createMedia(r, mediaManager, db, sessionMessages, INVERTEBRATE, id) } ren.Redirect("/invertebrate") } else { for k, msg := range errors { sessionMessages.AddDanger(k + ": " + msg) } ren.Redirect("/invertebrate/" + params["id"]) } }
func UpdateCoral(ren render.Render, mediaManager *media.Manager, r *http.Request, db *sql.DB, params martini.Params, sessionMessages *template.Messages) { id, _ := strconv.ParseInt(params["id"], 10, 64) coral := entity.NewCoral() coral.Populate(getCoralMap(r, params["id"])) val, errors := validation.ValidateCoral(coral, db, CORAL) if val { _, err := repository.UpdateCoral(coral, db, params["id"]) if err != nil { log.Println(err) sessionMessages.AddDanger("Failed to update coral.") } else { sessionMessages.AddSuccess("Successfully update coral.") updatePopularNames(db, id, CORAL, coral.GetPopularNames().GetValues()) createMedia(r, mediaManager, db, sessionMessages, CORAL, id) } ren.Redirect("/coral") } else { for k, msg := range errors { sessionMessages.AddDanger(k + ": " + msg) } ren.Redirect("/coral/" + params["id"]) } }
func EditInvertebrate(ren render.Render, db *sql.DB, params martini.Params, t *template.TemplateData) { var invertebrate_id string = params["id"] if invertebrate_id != "new" { invertebrate, err := repository.GetInvertebrate(db, invertebrate_id) if err != nil || invertebrate == nil { t.SessionMessage.AddDanger("Failed to load invertebrate.") ren.Redirect("/invertebrate") return } id, _ := strconv.ParseInt(params["id"], 10, 64) invertebrate.PopularNames.Names, err = repository.GetPopularNames(db, id, INVERTEBRATE) t.Data = invertebrate t.MediaList = getMediaList(db, INVERTEBRATE, id) ren.HTML(200, "blah/invertebrate/edit", t) } else { ren.HTML(200, "blah/invertebrate/edit", nil) } }
func CreateCoral(ren render.Render, mediaManager *media.Manager, r *http.Request, db *sql.DB, params martini.Params, sessionMessages *template.Messages) { coral := entity.NewCoral() coral.Populate(getCoralMap(r, "")) val, errors := validation.ValidateCoral(coral, db, CORAL) if val { res, err := repository.InsertCoral(coral, db) if err != nil { log.Println(err) sessionMessages.AddDanger("Failed to create coral.") } else { sessionMessages.AddSuccess("Successfully created coral.") id, _ := res.LastInsertId() insertPopularNames(db, id, CORAL, coral.GetPopularNames().GetValues()) createMedia(r, mediaManager, db, sessionMessages, CORAL, id) } ren.Redirect("/coral") } else { for k, msg := range errors { sessionMessages.AddDanger(k + ": " + msg) } ren.Redirect("/coral/new") } }
func EditCoral(ren render.Render, db *sql.DB, params martini.Params, t *template.TemplateData) { var coral_id string = params["id"] if coral_id != "new" { coral, err := repository.GetCoral(db, coral_id) if err != nil || coral == nil { t.SessionMessage.AddDanger("Failed to load coral.") ren.Redirect("/coral") return } id, _ := strconv.ParseInt(params["id"], 10, 64) coral.PopularNames.Names, err = repository.GetPopularNames(db, id, CORAL) t.Data = coral t.MediaList = getMediaList(db, CORAL, id) ren.HTML(200, "blah/coral/edit", t) } else { ren.HTML(200, "blah/coral/edit", nil) } }
func LoginPost(lu forms.Login, session sessions.Session, r render.Render, dbh *db.Dbh) { errs := ValidateLogin(&lu) if len(errs) > 0 { log.Printf("errors: %+v\n", errs) } user := dbh.GetUserByEmail(lu.Email) match := auth.MatchPassword(lu.Password, user.Password, user.Salt) if match { sessionkey := SessionKey(user.Email, user.Password, user.Salt) session.Set("loggedin", "true") session.Set("uid", user.Id) session.Set("email", user.Email) session.Set("key", sessionkey) dbh.CreateSession(models.UserSession{UserId: user.Id, SessionKey: sessionkey, Active: true, Timestamp: time.Now().Unix()}) r.Redirect(strings.Join([]string{utils.AppCfg.Url(), "albums"}, "/"), http.StatusFound) return } session.Set("flash", "Invalid Email or Password") r.Redirect(strings.Join([]string{utils.AppCfg.Url(), "login"}, "/"), http.StatusFound) }
// Handler to require a user to log in. If the user is currently logged in // nothing happens. Otherwise clear existing session and redirect the user // to the login page func RequireLogin(s sessions.Session, r render.Render) { session := s.Get("user_session") if session == nil { s.Clear() r.Redirect("/login") } }
func CreateAdmin(r render.Render, req *http.Request) { if len(cache.Users) > 0 { r.Error(404) return } if req.Method == "GET" { r.HTML(200, "user_add", map[string]interface{}{}) return } req.ParseForm() values := req.Form m := &model.User{} m.Account = values.Get("account") m.Password = model.Md5(values.Get("password")) m.Info = values.Get("info") m.Name = values.Get("name") if !checkNull([]string{m.Account, m.Password, m.Info, m.Name}...) { service.Logs.Error("args err") return } m.Status = model.UserStatusAdmin _, err := dao.AddUser(m) if err != nil { service.Logs.Error("dao.InsertUser err(%v)", err) return } r.Redirect("/", 302) return }
func (us UserService) SignOut(w http.ResponseWriter, req *http.Request, r render.Render) { // delete logged in session session, _ := utils.SessionStore.Get(req, "chroniton") session.Options.MaxAge = -1 session.Save(req, w) r.Redirect("/") }
func UpdateLatestNews(ren render.Render, r *http.Request, db *sql.DB, params martini.Params, sessionMessages *template.Messages) { latest_news := entity.NewLatestNews() latest_news.Populate(getLatestNewsMap(r)) val, errors := validation.ValidateLatestNews(latest_news, db, LATEST_NEWS) if val { _, err := repository.UpdateLatestNews(latest_news, db, params["id"]) if err != nil { log.Println(err) sessionMessages.AddDanger("Failed to upload news.") } else { sessionMessages.AddSuccess("Successfully upload news.") } ren.Redirect("/latest_news") } else { for k, msg := range errors { sessionMessages.AddDanger(k + ": " + msg) } ren.Redirect("/latest_news/" + params["id"]) } }
// Process register: check form, create new inactive user and send activation email func (self *RegisterController) ProcessRegister(params martini.Params, req *http.Request, r render.Render, di *di.DI) { userManager := di.UserManager() user := userManager.NewUser() // need validate user.Email = req.FormValue("Email") rawPassword := req.FormValue("Password") user.Password = userManager.CryptPassword(rawPassword) user.FullName = req.FormValue("FullName") user.Address = req.FormValue("Address") user.Phone = req.FormValue("Phone") user.IsActive = false user.Hash = userManager.GenerateHash(user.Email + user.FullName) userManager.Create(user) // send email mailer := di.Mailer() go mailer.Send(mailer.BuildRegistrationMail(user)) // message: "Activation link was sent to your email." r.Redirect("/users/") }
func createHub(user sessionauth.User, newHub hub, rend render.Render, req *http.Request) { var hubInDB hub query := r.Table("hub").Filter(r.Row.Field("name").Eq(newHub.HubName)) row, err := query.RunRow(dbSession) if err == nil && !row.IsNil() { // Register, error case. if err := row.Scan(&hubInDB); err != nil { fmt.Println("Error reading DB") } else { fmt.Println("User already exists. Redirecting to login.") } rend.Redirect(sessionauth.RedirectUrl) return } else { // User doesn't exist, continue with registration. if row.IsNil() { fmt.Println("User doesn't exist. Registering...") } else { fmt.Println(err) } } r.Table("hub").Insert(newHub).RunWrite(dbSession) fmt.Println("New hub done. Try to con") rend.Redirect(sessionauth.RedirectUrl) }
func CreatePlant(ren render.Render, mediaManager *media.Manager, r *http.Request, db *sql.DB, params martini.Params, sessionMessages *template.Messages) { plant := entity.NewPlant() plant.Populate(getPlantMap(r, "")) val, errors := validation.ValidateDefaultEntity(plant, db, PLANT) if val { res, err := repository.InsertPlant(plant, db) if err != nil { log.Println(err) sessionMessages.AddDanger("Failed to create plant.") } else { sessionMessages.AddSuccess("Successfully created plant.") id, _ := res.LastInsertId() insertPopularNames(db, id, PLANT, plant.GetPopularNames().GetValues()) createMedia(r, mediaManager, db, sessionMessages, PLANT, id) } ren.Redirect("/plant") } else { for k, msg := range errors { sessionMessages.AddDanger(k + ": " + msg) } ren.Redirect("/plant/new") } }
func DeleteComponent(ren render.Render, mediaManager *media.Manager, db *sql.DB, params martini.Params, sessionMessages *template.Messages) { var err error id, _ := strconv.ParseInt(params["id"], 10, 64) media_list := getMediaList(db, COMPONENT, id) if media_list != nil { _, errors := DeleteEntityMedia(*media_list, mediaManager, db) for _, err := range errors { log.Println(err) } _, err = repository.DeleteEntityMedia(db, id, COMPONENT) if err != nil { log.Println(err) sessionMessages.AddDanger("Failed to delete media for component.") } } _, err = repository.DeleteComponent(db, id) if err != nil { log.Println(err) sessionMessages.AddDanger("Failed to delete component.") } else { sessionMessages.AddSuccess("Successfully deleted component.") } ren.Redirect("/component") }
func PostLoginHandler(w http.ResponseWriter, rnd render.Render, r *http.Request, s *session.Session) { username := r.FormValue("username") password := r.FormValue("password") s.Username = username s.IsAuthorized = true fmt.Println(username) fmt.Println(password) token := jwt.New(jwt.SigningMethodHS256) token.Claims["Name"] = "token" token.Claims["exp"] = time.Now().Add(time.Minute * 5).Unix() tokenString, err := token.SignedString([]byte(session.TOKEN_STR)) fmt.Println(tokenString) if err != nil { w.WriteHeader(http.StatusInternalServerError) log.Printf("Token Signing error: %v\n", err) fmt.Fprintln(w, "Sorry, error while Signing Token!") } http.SetCookie(w, &http.Cookie{ Name: session.TOKEN_NAME, Value: tokenString, }) s.Id = tokenString storage, err := models.GetStorage() if err != nil { log.Fatalln(err) } storage.SaveUser(models.NewUser(username)) rnd.Redirect("/") }
func EditComponent(ren render.Render, db *sql.DB, params martini.Params, t *template.TemplateData) { var component_id string = params["id"] if component_id != "new" { component, err := repository.GetComponent(db, component_id) if err != nil || component == nil { t.SessionMessage.AddDanger("Failed to load component.") ren.Redirect("/component") return } t.Data = component id, _ := strconv.ParseInt(params["id"], 10, 64) t.MediaList = getMediaList(db, COMPONENT, id) ren.HTML(200, "blah/component/edit", t) } else { ren.HTML(200, "blah/component/edit", nil) } }
func PreventReauth(session sessions.Session, r render.Render) { _, ok := session.Get("id").(int64) if ok { session.AddFlash("warning: You are already signed in!") r.Redirect("/dashboard") } }
func CreateComponent(ren render.Render, mediaManager *media.Manager, r *http.Request, db *sql.DB, params martini.Params, sessionMessages *template.Messages) { component := entity.NewComponent() component.Populate(getComponentMap(r, "")) val, errors := validation.ValidateComponent(component, db, COMPONENT) if val { res, err := repository.InsertComponent(component, db) if err != nil { log.Println(err) sessionMessages.AddDanger("Failed to create component.") } else { sessionMessages.AddSuccess("Successfully created component.") id, _ := res.LastInsertId() createMedia(r, mediaManager, db, sessionMessages, "component", id) } ren.Redirect("/component") } else { for k, msg := range errors { sessionMessages.AddDanger(k + ": " + msg) } ren.Redirect("/component/new") } }
func UpdUserTodo(r render.Render, rq *http.Request) { for i := 0; i < 1; i++ { idStr := strings.TrimSpace(rq.FormValue("id")) id, err := strconv.ParseInt(idStr, 10, 64) if err != nil { break } username := strings.TrimSpace(rq.FormValue("username")) if len(username) == 0 { break } password := strings.TrimSpace(rq.FormValue("password")) if len(password) == 0 { break } user := make(map[string]interface{}, 2) user["username"] = username user["password"] = password models.UpdUser(id, user) } r.Redirect("/user/list") }
func UpdateComponent(ren render.Render, mediaManager *media.Manager, r *http.Request, db *sql.DB, params martini.Params, sessionMessages *template.Messages) { id, _ := strconv.ParseInt(params["id"], 10, 64) component := entity.NewComponent() component.Populate(getComponentMap(r, params["id"])) val, errors := validation.ValidateComponent(component, db, COMPONENT) if val { _, err := repository.UpdateComponent(component, db, params["id"]) if err != nil { log.Println(err) sessionMessages.AddDanger("Failed to update component.") } else { sessionMessages.AddSuccess("Successfully updated component.") createMedia(r, mediaManager, db, sessionMessages, COMPONENT, id) } ren.Redirect("/component") } else { for k, msg := range errors { sessionMessages.AddDanger(k + ": " + msg) } ren.Redirect("/component/" + params["id"]) } }
func getRegisterPage(user sessionauth.User, r render.Render) { if user.IsAuthenticated() { r.Redirect(INDEX_PAGE) return } r.HTML(200, REGISTER_PAGE, nil) }
func (c ReleaseWatchersController) WatchOrUnwatch(req *http.Request, r martrend.Render, params mart.Params) { action := req.FormValue("action") switch { case action == "watch": err := c.watchersRepo.Add(req.FormValue("relSource"), req.FormValue("minVersion")) if err != nil { r.HTML(500, c.errorTmpl, err) return } case action == "unwatch": err := c.watchersRepo.Remove(req.FormValue("relSource")) if err != nil { r.HTML(500, c.errorTmpl, err) return } default: r.HTML(500, c.errorTmpl, bosherr.New("Unknown action '%s'", action)) return } r.Redirect("/release_watchers") }