func SignUp(s sessions.Session, r render.Render, x csrf.CSRF) { returnvals := map[string]interface{}{ "csrf": x.GetToken(), "Title": "Nightcrawler Signup", } r.HTML(200, "sign_up", returnvals) }
func ReadListQnA(req *http.Request, r render.Render, db *mgo.Database) { appid := req.Header.Get("Application-Id") if appid == "" { r.JSON(handlers.HttpErr(http.StatusNotFound, "insert to Application-Id")) return } //// colQuerier := bson.M{} change := bson.M{"$set": bson.M{"reception": true}} CollectionName := handlers.CollectionNameQnA(appid) if _, err := db.C(CollectionName).UpdateAll(colQuerier, change); err != nil { r.JSON(handlers.HttpErr(http.StatusNotFound, err.Error())) return } var qnas []QnA if err := db.C(CollectionName).Find(bson.M{}).Sort("-time").All(&qnas); err != nil { r.JSON(handlers.HttpErr(http.StatusNotFound, err.Error())) return } if qnas == nil { r.JSON(http.StatusOK, map[string]interface{}{"return": bson.D{}}) return } r.JSON(http.StatusOK, map[string]interface{}{"return": qnas}) }
func getRegisterPage(user sessionauth.User, r render.Render) { if user.IsAuthenticated() { r.Redirect(INDEX_PAGE) return } r.HTML(200, REGISTER_PAGE, nil) }
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 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 (ac *AuthController) Login(user models.User, r render.Render) { getuser := models.User{} session := ac.session.DB(os.Getenv("DB_NAME")).C("users") err := session.Find(bson.M{"email": user.Email}).One(&getuser) if err != nil { panic(err) } err = bcrypt.CompareHashAndPassword([]byte(getuser.Password), []byte(user.Password)) if err != nil { panic(err) } token := jwt.New(jwt.GetSigningMethod("HS256")) token.Claims["user_id"] = getuser.Id token.Claims["email"] = getuser.Email token.Claims["exp"] = time.Now().Add(time.Minute * 5).Unix() tokenString, err := token.SignedString([]byte(SecretKey)) if err != nil { r.JSON(500, map[string]interface{}{"_error": "500: Signing Error."}) return } data := map[string]string{ "token": tokenString, } r.JSON(200, data) }
func genericResponseFormatter(r render.Render, apikey string, payload map[string]interface{}, extErr error) { var ( statusCode int err error res Response ) if extErr != nil { statusCode = FailureStatus res = Response{ ErrorMsg: extErr.Error(), } } else { if _, err = json.Marshal(payload); err != nil { statusCode = FailureStatus res = Response{ ErrorMsg: err.Error(), } } else { statusCode = SuccessStatus res = Response{ APIKey: apikey, Payload: payload, } } } r.JSON(statusCode, res) }
func GroupCreate(db gorm.DB, r render.Render, group models.Group) { if err := db.Save(&group).Error; err != nil { r.JSON(http.StatusConflict, map[string]interface{}{"error": "Group conflict"}) return } r.JSON(http.StatusCreated, group) }
func IndexHandler(rr render.Render, w http.ResponseWriter, r *http.Request) { var pp models.Post p := make([]models.Post, 0) namefs := utils.Getlistfileindirectory(Pathposts) tnamefs := namefs vsegopost := len(namefs) if len(namefs) != 0 { namefs = utils.SorttoDown(namefs) if Kolpost > len(namefs) { tnamefs = namefs[:] } else { tnamefs = namefs[:Kolpost] } for _, namef := range tnamefs { pp.GetPostfromFileMd(Pathposts + string(os.PathSeparator) + namef) if !pp.GetDraft() { // не отражаются черновики p = append(p, pp) } } } else { p = append(p, models.Post{Id: "ПОСТОВ НЕТ", Title: "ЭТОТ БЛОГ ПУСТ. ПРИХОДИТЕ ПОЗЖЕ ;)", ContentText: ""}) } rr.HTML(200, "index", &models.PagePost{TitlePage: "Блог проектов kaefik", Posts: p, Postright: vsegopost - Kolpost}) }
/** 更新 **/ func UpdateQuestion(r render.Render, req *http.Request) { c := appengine.NewContext(req) id, _ := strconv.Atoi(req.FormValue("Key")) key := datastore.NewKey(c, "Question", "", int64(id), nil) var question Question if err := datastore.Get(c, key, &question); err != nil { c.Criticalf(err.Error()) } question.Content = req.FormValue("Content") question.LargeCategoryKey = req.FormValue("LargeCategoryKey") question.MediumCategoryKey = req.FormValue("MediumCategoryKey") question.SmallCategoryKey = req.FormValue("SmallCategoryKey") question.Rubric = req.FormValue("Rubric") question.Percentage, _ = strconv.ParseFloat(req.FormValue("Percentage"), 64) question.Status = req.FormValue("Status") question.Level = req.FormValue("Level") question.UserKey = req.FormValue("UserKey") _, err := datastore.Put(c, key, &question) if err != nil { c.Criticalf("%s", err) r.JSON(400, err) } else { r.JSON(200, question) } }
func (ps ProjectService) Create(projet models.Project, r render.Render) { err := utils.ORM.Save(&projet).Error if err != nil { utils.Log.Error("Failed to create project: %v", err) r.HTML(403, "project/new", projet) } }
func DeleteItem(r render.Render, params martini.Params, c *redis.Client) { err := c.HDel("godo:items", params["id"]).Err() if err != nil { panic(err) } r.JSON(http.StatusOK, 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 awardUser(db *mgo.Database, session sessions.Session, r render.Render, x csrf.CSRF) { template := make(map[string]string) template["contactUrl"] = os.Getenv("CONTACT_URL") template["contactValue"] = os.Getenv("CONTACT_VALUE") user := session.Get("user").(string) status := checkStatus(db, user) if status == 0 { template["message"] = "Can't seem to find records of you :/" r.HTML(http.StatusUnauthorized, "error", template) } else if status == 1 { err := userHasAuth(db, user) if err != nil { log.Println(err) template["message"] = "Uh oh! Please report this :(" r.HTML(http.StatusInternalServerError, "error", template) } else { r.HTML(http.StatusOK, "form", x.GetToken()) } } else if status == 2 { r.HTML(http.StatusOK, "form", x.GetToken()) } else if status == 3 { template["message"] = "Hey buddy, it seems you have been awarded before." r.HTML(http.StatusUnauthorized, "error", template) } }
func updateUser(r render.Render, params martini.Params, re *http.Request, f *fishhub.DBService, userForm user.UserUpdateForm) { d := f.DB.Copy() defer d.Close() query := bson.M{"_id": bson.ObjectIdHex(params["id"])} update := bson.M{ "address": userForm.Address, "contactno": userForm.ContactNo, "country": userForm.Country, "email": userForm.Email, "locale": userForm.Locale, "name": userForm.Name, "notification": userForm.Notification, "role": userForm.Role, } err := d.Update("users", query, bson.M{"$set": update}) if err != nil { displayUnknownError(r) return } r.JSON(200, userForm) }
func recovery( c martini.Context, req *http.Request, ren render.Render, dec formDecoder, ) { defer func() { if r := recover(); r != nil { switch err := r.(type) { case jsonError: handleJsonError(err, ren) case authError: authenticate(err, dec, ren, req) case userError: ren.HTML(200, "error", m{ "Message": formatMessage(err.Error()), }) case csql.Error: ren.HTML(200, "error", m{ "Message": formatMessage(err.Error()), }) default: panic(r) } } }() c.Next() }
func ListBuckets(r render.Render, db database.Database) { if buckets, err := db.ListBuckets(); err != nil { JsonErrorf(r, http.StatusBadRequest, err.Error()) } else { r.JSON(http.StatusOK, buckets) } }
func webAuth( lg *log.Logger, c martini.Context, routes martini.Routes, params martini.Params, r *http.Request, w http.ResponseWriter, s *sessions.Session, ren render.Render, dec formDecoder, mdec multiDecoder, ) { userId := sessGet(s, sessionUserId) if len(userId) == 0 { panic(ae("")) } state := &web{ lg: lg, c: c, routes: routes, params: params, r: r, w: w, s: s, ren: ren, decode: dec, multiDecode: mdec, user: findUserById(userId), } ren.Template().Funcs(template.FuncMap{ "url": state.url, }) c.Map(state) }
//Get /users/:user_id/relationships func (u *UserHandler) GetAllRelations(request *http.Request, rd render.Render, params martini.Params) { // 获取 url 参数 userid, err := strconv.ParseInt(params["user_id"], 10, 64) if err != nil { rd.Text(400, "The request cannot be fulfilled due to bad syntax.") return } //验证 user 是否存在 _, err = u.userService.GetUser(userid) if err != nil { if err == pg.ErrNoRows { rd.Text(400, fmt.Sprintln("user", userid, "not exist")) } else { rd.Text(500, err.Error()) } return } rs, err := u.userService.GetUserRelations(userid) if err != nil { rd.Text(500, err.Error()) return } relations := make([]interface{}, 0, 0) for _, r := range rs { relations = append(relations, fmtRelationShip(r)) } rd.JSON(200, relations) }
func CollectionResponse(r render.Render, collection []interface{}, err error) { if err != nil { r.JSON(404, nil) } else { r.JSON(200, collection) } }
func MediaCreate(db gorm.DB, r render.Render, media models.Media) { if err := db.Save(&media).Error; err != nil { r.JSON(http.StatusConflict, map[string]interface{}{"error": "Media conflict"}) return } r.JSON(http.StatusCreated, media) }
func IndividualResponse(r render.Render, collection interface{}, err error) { if err != nil { r.JSON(404, nil) } else { r.JSON(200, collection) } }
func userInforEdit(session sessions.Session, r render.Render) { user_number := session.Get("user_number") user_name := session.Get("user_name") if user_number == nil || user_name == nil { r.HTML(200, "home", nil) } var name string var number string if value, ok := user_name.(string); ok { name = value } else { r.HTML(200, "home", nil) } if value, ok := user_number.(string); ok { number = value } else { r.HTML(200, "home", nil) } var user model.User user, err := model.GetUserInfo(name, number) if err != true { r.HTML(200, "home", nil) } else { r.HTML(200, "userInforEdit", user) } }
// Handler function for fan-out and fan-in func mosaic(f UploadForm, r render.Render) { t0 := time.Now() file, _ := f.Image.Open() original, _, _ := image.Decode(file) bounds := original.Bounds() db := cloneTilesDB() // fan-out c1 := cut(original, &db, f.TileSize, bounds.Min.X, bounds.Min.Y, bounds.Max.X/2, bounds.Max.Y/2) c2 := cut(original, &db, f.TileSize, bounds.Max.X/2, bounds.Min.Y, bounds.Max.X, bounds.Max.Y/2) c3 := cut(original, &db, f.TileSize, bounds.Min.X, bounds.Max.Y/2, bounds.Max.X/2, bounds.Max.Y) c4 := cut(original, &db, f.TileSize, bounds.Max.X/2, bounds.Max.Y/2, bounds.Max.X, bounds.Max.Y) // fan-in c := combine(bounds, c1, c2, c3, c4) buf1 := new(bytes.Buffer) jpeg.Encode(buf1, original, nil) originalStr := base64.StdEncoding.EncodeToString(buf1.Bytes()) t1 := time.Now() images := map[string]string{ "original": originalStr, "mosaic": <-c, "duration": fmt.Sprintf("%v ", t1.Sub(t0)), } r.HTML(200, "results", images) }
func Verify(res http.ResponseWriter, req *http.Request, r render.Render, dbh *db.Dbh) { pk := req.FormValue("user_private_key") a := req.FormValue("file_album") album := dbh.GetAlbum(a) if album.Id > 0 && album.Privatekey == pk { return } if pk == "" || pk != utils.ImageCfg.SecretKey() { log.Printf("Upload failed: Invalid Private Key (%s)\n", pk) r.JSON(http.StatusUnauthorized, Response{"error": http.StatusUnauthorized, "code": "Invalid Private Key", "name": a}) return } if a == "" { log.Printf("Upload failed: Invalid Album Name (%s)\n", a) r.JSON(http.StatusUnauthorized, Response{"error": http.StatusUnauthorized, "code": "Invalid Album Name", "name": a}) return } log.Println("verify: good") return }
func GoLoginHandler(r render.Render, params martini.Params) { path := params["path"] if path == "" { path = "/" } r.HTML(200, "admin/login", map[string]string{"path": path}) }
func getLoginPage(user sessionauth.User, r render.Render) { if user.IsAuthenticated() { r.Redirect(INDEX_PAGE) return } r.HTML(200, LOGIN_PAGE, nil) }
func createUser(r render.Render, re *http.Request, f *fishhub.DBService, userForm user.UserForm) { userExistError := binding.Error{ Message: "is already taken", FieldNames: []string{"email"}, Classification: "UserExistError", } errors := binding.Errors{userExistError} if userExist(f, userForm.UserId) { r.JSON(400, errors) return } d := f.DB.Copy() defer d.Close() query := bson.M{"userid": userForm.UserId} update := bson.M{"$set": userForm} updated, _ := d.Upsert("users", query, nil, update, true) if updated == true { r.JSON(200, map[string]interface{}{ "message": "User profile is successfully created.", }) return } displayUnknownError(r) }
// Index returns people func Index(render render.Render, r doorbot.Repositories, session *auth.Authorization) { repo := r.PersonRepository() people, err := repo.All(r.DB()) if err != nil { log.WithFields(log.Fields{ "error": err, "account_id": r.AccountScope(), }).Error("Api::People->Index database error") render.JSON(http.StatusInternalServerError, doorbot.NewInternalServerErrorResponse([]string{})) return } switch session.Type { case auth.AuthorizationAdministrator: render.JSON(http.StatusOK, PeopleViewModel{People: people}) case auth.AuthorizationDevice: render.JSON(http.StatusOK, PublicPeopleViewModel{People: newPublicPeople(people)}) case auth.AuthorizationPerson: if session.Person.IsAccountManager() { render.JSON(http.StatusOK, PeopleViewModel{People: people}) return } render.JSON(http.StatusOK, PublicPeopleViewModel{People: newPublicPeople(people)}) } }
func createNote(rend render.Render, req *http.Request, params martini.Params, dbh *db.DBHandle) { err := req.ParseForm() if err != nil { rend.JSON(http.StatusBadRequest, err.Error()) return } u := unmarshalNoteJSON{} err = json.NewDecoder(req.Body).Decode(&u) if err != nil { rend.JSON(http.StatusBadRequest, err.Error()) return } p := db.Person{Id: u.PersonId} err = dbh.ORM.Read(&p) if err != nil { rend.JSON(http.StatusInternalServerError, fmt.Sprintf("Unknown Person ID: %d", u.PersonId)) return } dbnote := db.Note{ Text: u.Text, Category: u.Category, Date: u.Date, Person: &p, } err = dbh.CreateNote(&dbnote) if err != nil { rend.JSON(http.StatusInternalServerError, err.Error()) return } rend.JSON(200, noteWithPersonIdJSON{&dbnote, p.Id}) }