コード例 #1
0
// TODO: validation
func UserUpdate(c web.C, w http.ResponseWriter, r *http.Request) {
	User := models.User{}
	User.Id, _ = strconv.ParseInt(c.URLParams["id"], 10, 64)
	db.Find(&User)
	User.Name = r.FormValue("Name")
	db.Save(&User)
	http.Redirect(w, r, "/user/index", 301)
}
コード例 #2
0
ファイル: account.go プロジェクト: adimare/japapp
// Validates user data, if it is correct the user is inserted in the db
func Register(user *models.User) (int, error) {
	user_id := 0

	// Check if the user already exists
	if models.UserExists(user.Fields["username"]) {
		return user_id, errors.New("user-exists")
	}

	// The user's password is hashed
	user.Fields["password"] = getPasswordHash(user.Fields["password"])

	// Insert the user in the database
	user_id = user.Insert()
	return user_id, nil
}
コード例 #3
0
ファイル: login.go プロジェクト: brewinvaz/agile-metrics
func (lc *LoginController) PostLogin(w http.ResponseWriter, r *http.Request) {
	var um *models.User

	decoder := json.NewDecoder(r.Body)
	if err := decoder.Decode(&um); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if !um.Authenticate(um) {
		http.Error(w, "Invalid username or password.", http.StatusUnauthorized)
		return
	}

}
コード例 #4
0
// CreateUser creates a new user resource
func (uc UserController) CreateUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	// Stub an user to be populated from the body
	u := models.User{}
	// Populate the user data
	json.NewDecoder(r.Body).Decode(&u)
	// Add an Id
	u.Id = bson.NewObjectId()
	// Write the user to mongo
	uc.session.DB("go_rest_tutorial").C("users").Insert(u)
	// Marshal provided interface into JSON structure
	uj, _ := json.Marshal(u)
	// Write content-type, statuscode, payload
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(201)
	fmt.Fprintf(w, "%s", uj)
}
コード例 #5
0
func UserUpdate(c web.C, w http.ResponseWriter, r *http.Request) {
	User := models.User{}
	User.Id, _ = strconv.ParseInt(c.URLParams["id"], 10, 64)
	db.Find(&User)
	User.Name = r.FormValue("Name")
	if err := models.UserValidate(User); err != nil {
		var Mess string
		errs := valval.Errors(err)
		for _, errInfo := range errs {
			Mess += fmt.Sprint(errInfo.Error)
		}
		tpl = template.Must(template.ParseFiles("view/user/edit.html"))
		tpl.Execute(w, FormData{User, Mess})
	} else {
		db.Save(&User)
		http.Redirect(w, r, "/user/index", 301)
	}
}
コード例 #6
0
ファイル: oauth.go プロジェクト: brewinvaz/agile-metrics
func (oc *OauthController) GetCallback(w http.ResponseWriter, r *http.Request) {

	// Generate config
	conf := oc.generateConfig()

	// Get the code from the request to callback handler
	code := r.URL.Query().Get("code")

	// Exchange code for access token
	token, err := conf.Exchange(oauth2.NoContext, code)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// Get user details
	client := conf.Client(oauth2.NoContext, token)
	userDetails, err := oc.retrieveUserDetails(client)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// Create or update user/token, persist to database
	userModel := new(models.User)
	_, isAlreadyRegistered := userModel.CreateOrUpdateUser(userDetails["data"].(map[string]interface{}), token)

	// Redirect user to appropriate landing page
	redirectPath := "/login"
	if !isAlreadyRegistered {
		redirectPath = "/register"
	}

	// Generate user cookie
	if cookie, err := oc.createSecureCookie(userModel); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	} else {
		http.SetCookie(w, cookie)
	}

	// Do not forget the path prefix
	http.Redirect(w, r, pathPrefix+redirectPath, http.StatusMovedPermanently)
}
コード例 #7
0
ファイル: register.go プロジェクト: brewinvaz/agile-metrics
func (rc *RegistrationController) PostRegistration(w http.ResponseWriter, r *http.Request) {
	var um *models.User

	decoder := json.NewDecoder(r.Body)
	if err := decoder.Decode(&um); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if registered, dbUserModel := um.GetUser(um.AsanaId); registered {
		http.Redirect(w, r, pathPrefix+"/login?registered=1", http.StatusMovedPermanently)
	} else if dbUserModel == nil {
		// Bad Asana Id. Should not have happened.
		http.Error(w, "Please login with Asana to continue registration. Invalid Asana Id.", http.StatusForbidden)
	} else {
		// Register User (Save to db)
		if ok, _ := dbUserModel.RegisterUser(um); !ok {
			http.Error(w, "Error occured during registration.", http.StatusInternalServerError)
		}
	}
}
コード例 #8
0
ファイル: utils.go プロジェクト: samolds/principia
// Builds a CommentData object from a models.Comment object with the proper fields
func BuildCommentData(ctx appengine.Context, comObj models.Comment, commentKey *datastore.Key) (models.CommentData, error) {
	var author models.User
	var sim models.Simulation
	var com models.CommentData

	authorKey := datastore.NewKey(ctx, "User", comObj.AuthorKeyName, 0, nil)
	err := datastore.Get(ctx, authorKey, &author)
	if err != nil {
		return com, err
	}

	var profileImageSrc string
	if len(string(author.ImageBlobKey)) > 0 {
		profileImageSrc = "/api/img/" + string(author.ImageBlobKey)
	}

	err = datastore.Get(ctx, commentKey.Parent(), &sim)
	if err != nil {
		return com, err
	}

	// Get all of the display names for each simulation author
	if author.DisplayName == "" {
		author.DisplayName = "Anonymous"
	}

	com.KeyName = comObj.KeyName
	com.Contents = comObj.Contents
	com.CreationDate = comObj.CreationDate
	com.PrettyCreationDate = comObj.CreationDate.Format("January _2, 2006")
	com.AuthorName = author.DisplayName
	com.AuthorID = author.KeyName
	com.AuthorImageSrcUrl = profileImageSrc
	com.SimulationName = sim.Name
	com.SimulationID = sim.KeyName
	com.SimulationType = sim.Type

	return com, nil
}
コード例 #9
0
ファイル: utils.go プロジェクト: samolds/principia
// Builds a SimulationData object from a models.Simulation object with the proper fields
func BuildSimulationData(ctx appengine.Context, simObj models.Simulation, simKey *datastore.Key) (models.SimulationData, error) {
	var author models.User
	var sim models.SimulationData

	authorKey := datastore.NewKey(ctx, "User", simObj.AuthorKeyName, 0, nil)
	err := datastore.Get(ctx, authorKey, &author)
	if err != nil {
		return sim, err
	}

	q := datastore.NewQuery("Rating").Ancestor(simKey)
	simFaves, err := q.Count(ctx)
	if err != nil {
		return sim, err
	}

	// Get the display name for the simulation author
	if author.DisplayName == "" {
		author.DisplayName = "Anonymous"
	}

	sim.KeyName = simObj.KeyName
	sim.Name = simObj.Name
	sim.Simulator = simObj.Simulator
	sim.Type = simObj.Type
	sim.Description = simObj.Description
	sim.CreationDate = simObj.CreationDate
	sim.UpdatedDate = simObj.UpdatedDate
	sim.ImageSrcUrl = "/api/img/" + string(simObj.ImageBlobKey)
	sim.IsPrivate = simObj.IsPrivate
	sim.AuthorName = author.DisplayName
	sim.AuthorID = author.KeyName
	sim.RatingTotal = simFaves

	return sim, nil
}
コード例 #10
0
ファイル: PPMSecond.go プロジェクト: hefju/PPMSecond
func SetRoute(m *martini.ClassicMartini) {
	//主页
	m.Get("/", func() string {
		return "<b>欢迎使用任务跟踪管理系统 version 0.1<b>"
	})
	m.Get("/json", func() []byte {
		result, _ := json.Marshal("欢迎使用任务跟踪管理系统 version 0.1")
		return result
	})
	m.Get("/task/json", func() []byte {
		output, _ := json.MarshalIndent(taskList, "  ", "    ")
		return output
	})

	m.Get("/task/json/:id", func(params martini.Params) []byte {
		id, _ := strconv.Atoi(params["id"])

		if len(taskList.List) > id {
			one := taskList.List[id]
			output, _ := json.MarshalIndent(one, "  ", "    ")
			return output
		} else {
			return []byte("<Task><Content>task not found.</Content></Task>")
		}
	})
	//所有任务
	m.Get("/task/all", func() string {
		return taskList.String()
	})
	m.Get("/task/xml", func() []byte {
		output, _ := xml.MarshalIndent(taskList, "  ", "    ")
		return output
	})
	m.Get("/task/xml/:id", func(params martini.Params) []byte {
		id, _ := strconv.Atoi(params["id"])

		if len(taskList.List) > id {
			one := taskList.List[id]
			output, _ := xml.MarshalIndent(one, "  ", "    ")
			return output
		} else {
			return []byte("<Task><Content>task not found.</Content></Task>")
		}
	})

	//单个任务
	m.Get("/task/:id", func(params martini.Params) string {
		id, _ := strconv.Atoi(params["id"])

		if len(taskList.List) > id {
			one := taskList.List[id]
			return one.String()
		} else {
			return "<b>task not found.<b>"
		}
	})

	//用户登录
	m.Get("/hello/:name", func(params martini.Params) string {
		var u models.User
		u.Id = 999
		u.Name = params["name"]
		fmt.Println(u)
		return "Hello " + params["name"]
	})
}
コード例 #11
0
ファイル: user.go プロジェクト: samolds/principia
// Displays a users profile page and handles updates to a logged in users profile information
func ProfileHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	userKeyName := vars["userID"]
	ctx := appengine.NewContext(r)

	// Get the page user information
	var pageUser models.User
	pageUserKey := datastore.NewKey(ctx, "User", userKeyName, 0, nil)
	err := datastore.Get(ctx, pageUserKey, &pageUser)
	if err != nil {
		controllers.ErrorHandler(w, r, "User was not found: "+err.Error(), http.StatusNotFound)
		return
	}

	// Check to see if the logged in user matches the page user
	userIsOwner := utils.IsOwner(userKeyName, ctx)

	// If a user is just viewing the page
	if r.Method == "GET" {
		var simulations []models.SimulationData

		// If viewing someone else's profile page, get their 8 most recent public simultions to display
		if !userIsOwner {
			// Build a query
			q := datastore.NewQuery("Simulation").Filter("AuthorKeyName =", userKeyName).Filter("IsPrivate =", false).Order("-CreationDate").Limit(8)
			simulations, err = utils.GetSimulationDataSlice(r, q)
			if err != nil {
				controllers.ErrorHandler(w, r, err.Error(), http.StatusInternalServerError)
				return
			}
		}

		// Nicely format the join date
		prettyJoinDate := pageUser.JoinDate.Format("January _2, 2006")
		var empty []models.Simulation
		totalFavoritesReceived := 0

		// Get the profile image they may or may not
		var userProfileImageSrc string
		if len(string(pageUser.ImageBlobKey)) > 0 {
			userProfileImageSrc = "/api/img/" + string(pageUser.ImageBlobKey)
		}

		// Only want to generate an image upload user if it is the user's profile page
		var imageUploadUrl string
		if userIsOwner {
			// The user's profile images need to be POSTed to specific appengine blobstore "action" paths.
			// Have to specify a path to return to after the post succeeds
			imageUpload, err := blobstore.UploadURL(ctx, r.URL.Path, nil)
			if err != nil {
				api.ApiErrorResponse(w, "Could not generate blobstore upload: "+err.Error(), http.StatusInternalServerError)
				return
			}
			imageUploadUrl = imageUpload.Path
		}

		// Get a count of all favorites received on all simulations created by this user
		q := datastore.NewQuery("Simulation").KeysOnly().Filter("AuthorKeyName =", userKeyName)
		simKeys, err := q.GetAll(ctx, &empty) // Get all simulation keys made by this user
		if err != nil {
			controllers.ErrorHandler(w, r, err.Error(), http.StatusInternalServerError)
			return
		}

		// Get a count of all of the favorites received for each simulation and add to total
		for _, key := range simKeys {
			q := datastore.NewQuery("Rating").Ancestor(key)
			simFaves, err := q.Count(ctx)
			if err != nil {
				controllers.ErrorHandler(w, r, err.Error(), http.StatusInternalServerError)
				return
			}

			totalFavoritesReceived += simFaves
		}

		data := map[string]interface{}{
			"user":                   pageUser,
			"userJoinDate":           prettyJoinDate,
			"userProfileImageSrc":    userProfileImageSrc,
			"imageUploadUrl":         imageUploadUrl,
			"userIsOwner":            userIsOwner,
			"simulations":            simulations,
			"totalFavoritesReceived": totalFavoritesReceived,
		}

		controllers.BaseHandler(w, r, "user/profile", data)
		return
	}

	// When a user tries to post information
	if r.Method == "POST" {
		// Make sure only the owner is trying to update the information
		if !userIsOwner {
			controllers.ErrorHandler(w, r, "Unauthorized update attempt: "+err.Error(), http.StatusInternalServerError)
			return
		}

		// Get all of the form values and blob image from the post
		blobs, formValues, err := blobstore.ParseUpload(r)
		if err != nil {
			controllers.ErrorHandler(w, r, "Bad blobstore form parse: "+err.Error(), http.StatusInternalServerError)
			return
		}

		// Only update the profile image if they posted a new one
		newImage := blobs["ProfileImage"]
		if len(newImage) != 0 {
			// Delete the old profile photo if they already had one
			err = blobstore.Delete(ctx, pageUser.ImageBlobKey)
			if err != nil {
				api.ApiErrorResponse(w, "Can't delete the blobstore image: "+err.Error(), http.StatusInternalServerError)
				return
			}

			pageUser.ImageBlobKey = newImage[0].BlobKey
		}

		displayName := formValues["DisplayName"][0]
		if len(displayName) > 50 {
			api.ApiErrorResponse(w, "Your Display Name must be shorter than 50 characters.", http.StatusInternalServerError)
			return
		}

		interests := formValues["Interests"][0]
		if len(interests) > 1500 {
			api.ApiErrorResponse(w, "Your Interests must be shorter than 1500 characters.", http.StatusInternalServerError)
			return
		}

		// Update user information
		pageUser.DisplayName = displayName
		pageUser.Interests = interests

		_, err = datastore.Put(ctx, pageUserKey, &pageUser)
		if err != nil {
			// Could not place the user in the datastore
			controllers.ErrorHandler(w, r, "Could not save user data: "+err.Error(), http.StatusInternalServerError)
			return
		}
	}
}