Beispiel #1
0
func GetCommit(c *gin.Context) {
	repo := session.Repo(c)

	parsed, err := token.ParseRequest(c.Request, func(t *token.Token) (string, error) {
		return repo.Hash, nil
	})
	if err != nil {
		c.AbortWithError(http.StatusBadRequest, err)
		return
	}
	if parsed.Text != repo.FullName {
		c.AbortWithStatus(http.StatusUnauthorized)
		return
	}

	commit := c.Param("sha")
	branch := c.Query("branch")
	if len(branch) == 0 {
		branch = repo.Branch
	}

	build, err := store.GetBuildCommit(c, repo, commit, branch)
	if err != nil {
		c.AbortWithError(http.StatusNotFound, err)
		return
	}

	c.JSON(http.StatusOK, build)
}
Beispiel #2
0
func GetBuild(c *gin.Context) {
	if c.Param("number") == "latest" {
		GetBuildLast(c)
		return
	}

	repo := session.Repo(c)
	num, err := strconv.Atoi(c.Param("number"))
	if err != nil {
		c.AbortWithError(http.StatusBadRequest, err)
		return
	}

	build, err := store.GetBuildNumber(c, repo, num)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}
	jobs, _ := store.GetJobList(c, build)

	out := struct {
		*model.Build
		Jobs []*model.Job `json:"jobs"`
	}{build, jobs}

	c.IndentedJSON(http.StatusOK, &out)
}
Beispiel #3
0
func WhiskyListR(c *gin.Context) {
	// dependency injection
	var (
		whiskyStore = c.MustGet(WhiskyStoreKey).(WhiskyStore)
		user        = GetUser(c)
	)

	// get whiskies
	list, err := whiskyStore.GetAllWhiskies()
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	// transform list into alphabet map
	whiskies := map[string][]Whisky{}
	for _, whisky := range list {
		group := strings.ToUpper(whisky.Distillery[0:1])
		whiskies[group] = append(whiskies[group], whisky)
	}

	c.HTML(http.StatusOK, "list.html", gin.H{
		"User":     user,
		"Whiskies": whiskies,
	})
}
Beispiel #4
0
func (s *Server) getTagsFile(c *gin.Context) {
	id := c.Param("id")
	content_path := c.Param("path")[1:] // '/' を消す
	tag, err := TagFileFromFile(s.tagFilepath(id))
	if err != nil {
		c.AbortWithError(500, err)
		return
	}

	bucket, err := tag.Bucket(s)
	if err != nil {
		c.AbortWithError(500, err)
		return
	}

	content, found := bucket.Contents[content_path]
	if !found {
		c.AbortWithError(500, fmt.Errorf("content %s not found", content_path))
		return
	}

	content_body, err := ioutil.ReadFile(s.hashFilepath(content.Hash))
	if err != nil {
		c.AbortWithError(500, err)
		return
	}

	content_body, err = decode(content_body, tag.EncryptKey, tag.EncryptIv, content.Attr)
	if err != nil {
		c.AbortWithError(500, err)
		return
	}

	c.Data(200, "text/plain", content_body)
}
Beispiel #5
0
func (m *PresencesController) create(ctx *gin.Context) {

	presenceIn, topic, e := m.preCheckTopic(ctx)
	if e != nil {
		return
	}

	user, e := m.preCheckUser(ctx)
	if e != nil {
		return
	}

	isReadAccess := topic.IsUserReadAccess(user)
	if !isReadAccess {
		e := errors.New("No Read Access to topic " + presenceIn.Topic + " for user " + user.Username)
		ctx.AbortWithError(http.StatusForbidden, e)
		ctx.JSON(http.StatusForbidden, e)
		return
	}

	var presence = models.Presence{}
	err := presence.Upsert(user, topic, presenceIn.Status)
	if err != nil {
		log.Errorf("Error while InsertPresence %s", err)
		ctx.AbortWithError(http.StatusInternalServerError, err)
		ctx.JSON(http.StatusInternalServerError, err)
		return
	}

	go models.WSPresence(&models.WSPresenceJSON{Action: "create", Presence: presence})

	//out := &presenceJSONOut{Presence: presence}
	//ctx.JSON(http.StatusCreated, nil)
}
func (u *AccountHandler) sendLoginToken(c *gin.Context, player *ge.PlayerStruct) {
	if token, err := u.createLoginToken(player); err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
	} else {
		c.JSON(http.StatusOK, gin.H{"Token": token})
	}
}
Beispiel #7
0
func CallRpcServiceWithContext(c *gin.Context, env Env, name, method string, req interface{}, res rpcResponse) bool {

	// Get the service TCP client
	client, err := getEnvTcpClient(name, env)
	if goutils.HasErrorAndPrintStack(err) {
		c.AbortWithError(http.StatusInternalServerError, err)
		return true
	}

	err = client.Call(method, req, res)
	if err != nil {

		// Check if it is not found error
		if err.Error() == "not found" {
			c.AbortWithStatus(http.StatusNotFound)
		} else {
			goutils.PrintStackAndError(err)
			c.AbortWithError(http.StatusInternalServerError, err)
		}
		return true
	}

	if res.HasError() {
		c.JSON(http.StatusBadRequest, res.ReturnErrorMap())
		return true
	}

	return false
}
Beispiel #8
0
func (rc *ResourceController) GetResource(ctx *gin.Context) {
	var id bson.ObjectId
	req := ctx.Request
	resourceType := getResourceType(req.URL)

	// Validate id as a bson Object ID
	id, err := toBsonObjectID(ctx.Param("id"))
	if err != nil {
		ctx.AbortWithError(http.StatusBadRequest, err)
		return
	}
	logger.Log.WithFields(
		logrus.Fields{"resource type": resourceType, "id": id}).Info("GetResource")

	resource, err := rc.LoadResource(resourceType, id)
	if err != nil {
		if err == mgo.ErrNotFound {
			ctx.String(http.StatusNotFound, "Not Found")
			ctx.Abort()
			return
		} else {
			ctx.AbortWithError(http.StatusBadRequest, err)
			return
		}
	}

	logger.Log.WithFields(logrus.Fields{"resource": resource}).Info("GetResource")

	ctx.JSON(http.StatusOK, resource)
}
Beispiel #9
0
func PatientEmrAttachments(r *gin.Context) {
	id := r.Param("id")
	if id == "" {
		r.AbortWithStatus(http.StatusBadRequest)
		return
	}

	var query string
	var err error
	var o []patientEmrAttachmentsResult

	module := r.Param("module")
	if module == "" {
		query = "SELECT p.patient AS patient, p.module AS module, p.oid AS oid, p.annotation AS annotation, p.summary AS summary, p.stamp AS stamp, DATE_FORMAT(p.stamp, '%m/%d/%Y') AS date_mdy, m.module_name AS type, m.module_class AS module_namespace, p.locked AS locked, p.id AS id FROM patient_emr p LEFT OUTER JOIN modules m ON m.module_table = p.module WHERE p.patient = ? AND m.module_hidden = 0"
		_, err = model.DbMap.Select(&o, query, id)
	} else {
		query = "SELECT p.patient AS patient, p.module AS module, p.oid AS oid, p.annotation AS annotation, p.summary AS summary, p.stamp AS stamp, DATE_FORMAT(p.stamp, '%m/%d/%Y') AS date_mdy, m.module_name AS type, m.module_class AS module_namespace, p.locked AS locked, p.id AS id FROM patient_emr p LEFT OUTER JOIN modules m ON m.module_table = p.module WHERE p.patient = ? AND p.module = ? AND m.module_hidden = 0"
		_, err = model.DbMap.Select(&o, query, id, module)
	}

	if err != nil {
		log.Print(err.Error())
		r.AbortWithError(http.StatusInternalServerError, err)
		return
	}
	r.JSON(http.StatusOK, o)
	return
}
Beispiel #10
0
func (u *userHandler) Edit(c *gin.Context) {
	var user models.User

	currentUser := utils.MustGetCurrentUser(c)

	if err := c.Bind(&user); err != nil {
		errors := userResource.ParseError(err)
		if len(errors) > 0 {
			c.Error(errors[0])
			return
		}
	}
	userId := c.Param("userId")

	if currentUser.Role != models.Admin {
		user.Role = models.NormalUser
	}
	if currentUser.Role == models.NormalUser {
		user.DeleteAt = nil
	}

	if err := userResource.Edit(userId, &user); err != nil {
		c.AbortWithError(400, err)
		return
	}
	c.JSON(200, user)
}
Beispiel #11
0
func CategoriesHandler(context *gin.Context, database *db.Context) {
	result, err := database.Categories()
	if err != nil {
		context.AbortWithError(http.StatusInternalServerError, err)
	}
	context.JSON(http.StatusOK, result)
}
Beispiel #12
0
func (u *users) Authorize(c *gin.Context) {
	var user model.User
	db := database.GetDB()

	if err := c.Bind(&user); err != nil {
		c.AbortWithError(http.StatusBadRequest, err)
	} else {
		if id, err := user.Auth(db); err != nil {
			c.AbortWithError(http.StatusBadRequest, errors.New("Password or email incorrect"))
		} else if u, err := url.Parse(c.Request.Referer()); err != nil {
			c.AbortWithError(http.StatusBadRequest, err)
		} else {
			s := session.GetSession(c.Request)
			s.Values["user_id"] = id
			session.Save(c.Request, c.Writer)

			q := u.Query()

			if err := db.Model(&user).Preload("Role").Preload("Organization").First(&user, id).Error; err != nil {
				c.AbortWithError(http.StatusInternalServerError, err)
			} else if q.Get("response_type") != "code" || q.Get("client_id") == "" || q.Get("redirect_uri") == "" {
				c.AbortWithError(http.StatusBadRequest, errors.New("Unsupported request"))
			} else {
				params := url.Values{}
				params.Add("response_type", q.Get("response_type"))
				params.Add("client_id", q.Get("client_id"))
				params.Add("redirect_uri", q.Get("redirect_uri"))
				params.Add("scope", q.Get("scope"))
				c.Redirect(http.StatusFound, "/auth?"+params.Encode())
			}
		}
	}
}
Beispiel #13
0
func _createMenu(c *gin.Context) {
	var btn1 menu.Button
	var btn1_sub1 menu.Button
	var btn1_sub2 menu.Button
	btn1_sub1.SetAsScanCodePushButton("push", "push")
	btn1_sub2.SetAsScanCodeWaitMsgButton("waitmsg", "waitmsg")
	var btn1_subs = []menu.Button{btn1_sub1, btn1_sub2}
	btn1.SetAsSubMenuButton("扫毛", btn1_subs)
	var btn2 menu.Button
	btn2.SetAsLocationSelectButton("车位号", "location")
	btns := []menu.Button{btn1, btn2}

	var menu_ menu.Menu
	menu_.Buttons = btns
	err := menu.Create(global.WechatClient, &menu_)
	var wxMenu = &model.WXMenu{
		Id: bson.NewObjectId(),
		Menu: menu.Menu{
			Buttons: btns,
		},
	}

	log.Println("创建菜单 ", err)
	err = mgowrap.Save(wxMenu)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}
	log.Println("保存menu")

}
Beispiel #14
0
func CreateMenu(c *gin.Context) {
	var btn1 menu.Button
	btn1.SetAsScanCodeWaitMsgButton("扫码", "park")
	var btn2 menu.Button
	btn2.SetAsLocationSelectButton("锁号", "number")
	var btn3 menu.Button
	btn3.SetAsClickButton("充值", "encharge")
	var btn4 menu.Button
	btn4.SetAsClickButton("我的", "my")

	btns := []menu.Button{btn1, btn2, btn3, btn4}
	var menu_ menu.Menu
	menu_.Buttons = btns
	err := menu.Create(global.WechatClient, &menu_)
	var wxMenu = &model.WXMenu{
		Id: bson.NewObjectId(),
		Menu: menu.Menu{
			Buttons: btns,
		},
	}

	log.Println("创建菜单 ", err)
	err = mgowrap.Save(wxMenu)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}
	log.Println("保存menu")
}
Beispiel #15
0
// Delete deletes requested topic only if user is Tat admin, or admin on topic
func (t *TopicsController) Delete(ctx *gin.Context) {

	topicRequest, err := GetParam(ctx, "topic")
	if err != nil {
		return
	}

	var user = models.User{}
	err = user.FindByUsername(utils.GetCtxUsername(ctx))
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Error while fetching user."})
		return
	}

	paramJSON := paramTopicUserJSON{
		Topic:     topicRequest,
		Username:  user.Username,
		Recursive: false,
	}

	topic, e := t.preCheckUser(ctx, &paramJSON)
	if e != nil {
		return
	}
	err = topic.Delete(&user)
	if err != nil {
		ctx.AbortWithError(http.StatusInternalServerError, errors.New(err.Error()))
		return
	}
	ctx.JSON(http.StatusOK, "")
}
Beispiel #16
0
// FriendshipShow takes a given ID from gin.Context
// @returns a specific friendship JSON object
func FriendshipShow(c *gin.Context) {
	friendship := models.Friendship{}

	if database.DBCon.First(&friendship, c.Param("id")).RecordNotFound() {
		c.AbortWithError(http.StatusNotFound, appError.RecordNotFound).
			SetMeta(appError.RecordNotFound)
		return
	}

	var fd models.FriendshipData

	database.DBCon.First(&friendship.User, friendship.UserID)
	database.DBCon.First(&friendship.Friend, friendship.FriendID)
	database.DBCon.First(&fd, friendship.FriendshipDataID)

	if friendship.UserID == fd.PositiveUserID {
		friendship.Balance = fd.Balance
	} else {
		friendship.Balance = -fd.Balance
	}

	data, err := jsonapi.Marshal(friendship)

	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err).
			SetMeta(appError.JSONParseFailure)
		return
	}

	c.Data(http.StatusOK, "application/vnd.api+json", data)
}
Beispiel #17
0
func (t *TopicsController) preCheckUserAdminOnTopic(ctx *gin.Context, topicName string) (models.Topic, error) {
	topic := models.Topic{}
	errfinding := topic.FindByTopic(topicName, true)
	if errfinding != nil {
		e := errors.New(errfinding.Error())
		ctx.AbortWithError(http.StatusInternalServerError, e)
		return topic, e
	}

	if utils.IsTatAdmin(ctx) { // if Tat admin, ok
		return topic, nil
	}

	user, err := PreCheckUser(ctx)
	if err != nil {
		return models.Topic{}, err
	}

	if !topic.IsUserAdmin(&user) {
		e := fmt.Errorf("user %s is not admin on topic %s", user.Username, topic.Topic)
		ctx.AbortWithError(http.StatusForbidden, e)
		return models.Topic{}, e
	}

	return topic, nil
}
Beispiel #18
0
func (rc *ResourceController) GetResources(ctx *gin.Context) {
	req := ctx.Request
	resourceType := getResourceType(req.URL)

	logger.Log.WithFields(
		logrus.Fields{"resource type": resourceType}).Info("GetResources")

	resources := ptm_models.NewSliceForResourceName(resourceType, 0, 0)
	c := rc.Database().C(ptm_models.GetCollectionName(resourceType))
	// retrieve all documents in the collection
	// TODO Restrict this to resource type, just to be extra safe
	query := buildSearchQuery(resourceType, ctx)
	logger.Log.WithFields(
		logrus.Fields{"query": query}).Info("GetResources")
	err := c.Find(query).All(resources)
	if err != nil {
		if err == mgo.ErrNotFound {
			ctx.String(http.StatusNotFound, "Not Found")
			ctx.Abort()
			return
		} else {
			ctx.AbortWithError(http.StatusBadRequest, err)
			return
		}
	}

	ctx.JSON(http.StatusOK, resources)
}
Beispiel #19
0
func (h *StaticHandler) Handle(c *gin.Context) {
	if !h.Cache {
		c.Writer.Header().Add("Cache-Control",
			"no-cache, no-store, must-revalidate")
		c.Writer.Header().Add("Pragma", "no-cache")
		c.Writer.Header().Add("Expires", "0")
	}

	path := filepath.Join(h.Root, filepath.FromSlash(
		filepath.Clean("/"+c.Param("filepath"))))

	isDir, err := IsDirectory(path)
	if err != nil {
		c.AbortWithError(500, err)
		return
	}

	ok := false
	if isDir {
		ok, err = h.HandleDirList(path, c)
		if err != nil {
			c.AbortWithError(500, err)
			return
		}
	}

	if !ok {
		if h.ContentType != "" {
			c.Writer.Header().Add("Content-Type", h.ContentType)
		}
		h.fileServer.ServeHTTP(c.Writer, c.Request)
	}
}
Beispiel #20
0
func Generate8bit(c *gin.Context) {
	name := c.Param("name")
	gender := c.Param("gender")

	switch {
	case gender == "m":
		gender = "male"
	case gender == "f":
		gender = "female"
	case gender == "male" || gender == "female":
		//do nothing
	default:
		c.AbortWithError(http.StatusInternalServerError, errors.New("Invalid parameters"))
		return
	}

	log.Println(name)
	InitAssets()
	img := GenerateIdenticon8bits(gender, []byte(name))
	c.Header("Content-Type", "image/png")
	c.Stream(func(w io.Writer) bool {
		png.Encode(w, img)
		return false
	})
}
Beispiel #21
0
Datei: users.go Projekt: ovh/tat
// List list all users matching Criteria
func (u *UsersController) List(ctx *gin.Context) {
	criteria := u.buildCriteria(ctx)

	listAsAdmin := false
	if isTatAdmin(ctx) {
		listAsAdmin = true
	} else {
		user, e := PreCheckUser(ctx)
		if e != nil {
			ctx.AbortWithError(http.StatusInternalServerError, e)
			return
		}
		listAsAdmin = user.CanListUsersAsAdmin
	}
	count, users, err := userDB.ListUsers(criteria, listAsAdmin)
	if err != nil {
		ctx.AbortWithError(http.StatusInternalServerError, err)
		return
	}
	out := &tat.UsersJSON{
		Count: count,
		Users: users,
	}
	ctx.JSON(http.StatusOK, out)
}
Beispiel #22
0
func suggest(c *gin.Context) {

	cfg := getConfig(c)

	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	for {

		movie, err := cfg.Store.GetRandom()

		if err != nil {
			continue
		}

		if err := conn.WriteJSON(movie); err != nil {
			c.AbortWithError(http.StatusInternalServerError, err)
			return
		}

		time.Sleep(socketWaitFor)
	}

}
Beispiel #23
0
// FriendshipIndex takes in query params through
// gin.Context and is restricted to the currentUser
// @returns an array of friendship JSON objects
func FriendshipIndex(c *gin.Context) {
	friendships := []models.Friendship{}
	var curUser models.User
	database.DBCon.First(&curUser, c.Keys["CurrentUserID"])

	database.DBCon.Model(&curUser).Related(&friendships, "Friendships")

	// Get user and friend and friendshipData
	// TODO: n + 1 query problem here, so we'll figure this out later
	for i := range friendships {
		var fd models.FriendshipData
		database.DBCon.First(&friendships[i].Friend, friendships[i].FriendID)
		database.DBCon.First(&fd, friendships[i].FriendshipDataID)

		if curUser.ID == fd.PositiveUserID {
			friendships[i].Balance = fd.Balance
		} else {
			friendships[i].Balance = -fd.Balance
		}

		friendships[i].User = curUser
	}

	data, err := jsonapi.Marshal(friendships)

	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err).
			SetMeta(appError.JSONParseFailure)
		return
	}

	c.Data(http.StatusOK, "application/vnd.api+json", data)
}
Beispiel #24
0
func GetAddonFiles(ctx *gin.Context) {
	user := ctx.Params.ByName("user")
	repository := ctx.Params.ByName("repository")
	filepath := ctx.Params.ByName("filepath")[1:] // strip the leading "/"
	log.Info("Request for: " + filepath)

	lastReleaseTag, lastReleaseBranch := getLastRelease(user, repository)

	switch filepath {
	case "addons.xml":
		GetAddonsXML(ctx)
		return
	case "addons.xml.md5":
		GetAddonsXMLChecksum(ctx)
		writeChangelog(user, repository)
		return
	case "fanart.jpg":
		fallthrough
	case "icon.png":
		ctx.Redirect(302, fmt.Sprintf(githubUserContentURL+"/"+filepath, user, repository, lastReleaseBranch))
		return
	}

	switch {
	case addonZipRE.MatchString(filepath):
		addonZip(ctx, user, repository, lastReleaseTag)
	case addonChangelogRE.MatchString(filepath):
		addonChangelog(ctx, user, repository)
	default:
		ctx.AbortWithError(404, errors.New(filepath))
	}
}
Beispiel #25
0
func convertByFileHandler(c *gin.Context) {
	s := c.MustGet("statsd").(*statsd.Client)
	r, ravenOk := c.Get("sentry")

	file, header, err := c.Request.FormFile("file")
	if err != nil {
		c.AbortWithError(http.StatusBadRequest, ErrFileInvalid).SetType(gin.ErrorTypePublic)
		s.Increment("invalid_file")
		return
	}

	ext := c.Query("ext")

	source, err := converter.NewConversionSource("", file, ext)
	if err != nil {
		s.Increment("conversion_error")
		if ravenOk {
			r.(*raven.Client).CaptureError(err, map[string]string{"url": header.Filename})
		}
		c.Error(err)
		return
	}

	conversionHandler(c, *source)
}
Beispiel #26
0
func addonZip(ctx *gin.Context, user string, repository string, lastReleaseTag string) {
	release := getReleaseByTag(user, repository, lastReleaseTag)
	// if there a release with an asset that matches a addon zip, use it
	if release != nil {
		client := github.NewClient(nil)
		assets, _, _ := client.Repositories.ListReleaseAssets(user, repository, *release.ID, nil)
		platformStruct := xbmc.GetPlatform()
		platform := platformStruct.OS + "_" + platformStruct.Arch
		var assetAllPlatforms string
		for _, asset := range assets {
			if strings.HasSuffix(*asset.Name, platform+".zip") {
				assetPlatform := *asset.BrowserDownloadURL
				log.Info("Using release asset for " + platform + ": " + assetPlatform)
				ctx.Redirect(302, assetPlatform)
				return
			}
			if addonZipRE.MatchString(*asset.Name) {
				assetAllPlatforms = *asset.BrowserDownloadURL
				log.Info("Found all platforms release asset: " + assetAllPlatforms)
				continue
			}
		}
		if assetAllPlatforms != "" {
			log.Info("Using release asset for all platforms: " + assetAllPlatforms)
			ctx.Redirect(302, assetAllPlatforms)
			return
		}
	}
	ctx.AbortWithError(404, errors.New("Release asset not found."))
}
Beispiel #27
0
func (m *MessagesController) updateMessage(ctx *gin.Context, messageIn *messageJSON, message models.Message, user models.User, topic models.Topic) {
	info := ""
	if messageIn.Action == "update" {

		if !topic.CanUpdateMsg && !topic.CanUpdateAllMsg {
			ctx.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("You can't update a message on topic %s", topic.Topic)})
			return
		}

		if !topic.CanUpdateAllMsg && message.Author.Username != user.Username {
			ctx.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("Could not update a message from another user %s than you %s", message.Author.Username, user.Username)})
			return
		}

		message.Text = messageIn.Text
		err := message.Update(user, topic)
		if err != nil {
			log.Errorf("Error while update a message %s", err)
			ctx.AbortWithError(http.StatusInternalServerError, err)
			return
		}
		info = fmt.Sprintf("Message updated in %s", topic.Topic)
	} else {
		ctx.AbortWithError(http.StatusBadRequest, errors.New("Invalid action : "+messageIn.Action))
		return
	}
	go models.WSMessage(&models.WSMessageJSON{Action: messageIn.Action, Username: user.Username, Message: message})
	out := &messageJSONOut{Message: message, Info: info}
	ctx.JSON(http.StatusOK, out)
}
Beispiel #28
0
func HomeR(c *gin.Context) {
	// dependency injection
	var (
		whiskyStore = c.MustGet(WhiskyStoreKey).(WhiskyStore)
		reviewStore = c.MustGet(ReviewStoreKey).(ReviewStore)
		user        = GetUser(c)
	)

	// temporary variables
	var (
		activity []Review
		trending []Whisky
		err      error
	)

	// get activity stream for user
	activity, err = reviewStore.GetActivity(user.ID, LIMIT)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	// get trending whiskies
	trending, err = whiskyStore.GetTrending(LIMIT)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	c.HTML(http.StatusOK, "home.html", gin.H{
		"User":     user,
		"Activity": activity,
		"Trending": trending,
	})
}
Beispiel #29
0
func EditReviewFormR(c *gin.Context) {
	// dependency injection
	var (
		reviewStore = c.MustGet(ReviewStoreKey).(ReviewStore)
		user        = GetUser(c)
	)

	// only authenticated users can perform this action
	if !user.Authenticated() {
		c.AbortWithStatus(http.StatusUnauthorized)
		return
	}

	// fetch review
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.AbortWithError(http.StatusBadRequest, err)
		return
	}

	review, err := reviewStore.GetReview(id)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	c.HTML(http.StatusOK, "review-form.html", gin.H{
		"Action": "Edit",
		"User":   user,
		"Form":   review,
		"Errors": map[string]string{},
	})
}
Beispiel #30
-1
func UserListR(c *gin.Context) {
	// dependency injection
	var (
		userStore = c.MustGet(UserStoreKey).(UserStore)
		user      = GetUser(c)
	)

	// get users
	list, err := userStore.GetAllUser()
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	// transform list into alphabet map
	users := map[string][]User{}
	for _, user := range list {
		group := strings.ToUpper(user.Name[0:1])
		users[group] = append(users[group], user)
	}

	c.HTML(http.StatusOK, "users.html", gin.H{
		"User":  user,
		"Users": users,
	})
}