Exemplo n.º 1
0
func PostChirp(c *gin.Context) {
	var chirp model.Chirp
	body, err := ioutil.ReadAll(c.Request.Body)
	if err != nil {
		c.JSON(400, gin.H{"message": sys.ERR_READ_BODY, "status": sys.FAIL})
		return
	}

	err = json.Unmarshal(body, &chirp)
	if err != nil {
		c.JSON(500, gin.H{"message": sys.ERR_UNMARSHAL_BODY, "status": sys.FAIL, "payload": body})
		return
	}

	uid, _ := c.Get("userid")
	chirp.Userid, _ = Atoi(uid.(string))

	row := util.DB.QueryRow(chirp.StmtInsert())
	err = row.Scan(&chirp.Id)
	if err != nil {
		c.JSON(500, gin.H{"message": sys.ERR_DB_INSERT, "status": sys.FAIL, "payload": body})
		return
	}
	c.JSON(200, gin.H{"payload": chirp.Id, "status": sys.SUCCESS})
}
Exemplo n.º 2
0
func getContext(c *gin.Context) (tmpl string, context map[string]interface{}, err error) {
	tmplName, tmplNameExists := c.Get("tmpl")
	tmplNameValue, isString := tmplName.(string)
	tmplData, tmplDataExists := c.Get("data")

	// 模板未定义
	if !tmplNameExists || !isString {
		return "", nil, errors.New("No tmpl defined!")
	}

	// 公共模板数据
	commonDatas := getCommonContext(c)

	// 模板数据
	if tmplData != nil && tmplDataExists {
		contextData, isMap := tmplData.(map[string]interface{})

		if isMap {
			for key, value := range commonDatas {
				contextData[key] = value
			}

			return tmplNameValue, contextData, nil
		}
	}

	return tmplNameValue, commonDatas, nil

}
Exemplo n.º 3
0
func NewMessage(c *gin.Context) {
	user, _ := c.Get("User")

	username := user.(middleware.Userinfo).Username
	sid, _ := c.Get("Sid")
	fmt.Println("sid--->", sid)

	var msg Message
	err := c.BindJSON(&msg)
	if err == nil {
		//fmt.Printf("%#v\n", msg)
		conn := db.GetConnection()
		//fmt.Println("--->", username)
		if msg.Body == "" {
			return
		}
		if username == "" {
			c.JSON(400, gin.H{"error": "session expired"})
			return
		}
		insert_message(conn, msg.Body, username)
		if msg.To != "" {
			//fmt.Println("go to:", msg.To)
			c.JSON(http.StatusOK, gin.H{"status": "have to", "body": "you say: " + msg.Body})
		} else {
			//fmt.Println("to all")
			c.JSON(http.StatusOK, gin.H{"status": "to all", "body": "you say: " + msg.Body})
		}
		return
	}
	fmt.Println("err===", err)
	c.JSON(400, gin.H{"error": err})
}
Exemplo n.º 4
0
Arquivo: api.go Projeto: P0rtk3y/api
func HandleRun(c *gin.Context) {
	req, err := ParseRequest(c.Request)
	if err != nil {
		errorResponse(400, err, c)
		return
	}

	config, exists := c.Get("config")
	if !exists {
		errorResponse(400, fmt.Errorf("Cant get config"), c)
		return
	}

	client, exists := c.Get("client")
	if !exists {
		errorResponse(400, fmt.Errorf("Cant get client"), c)
		return
	}

	run := NewRun(config.(*Config), client.(*docker.Client), req)
	defer run.Destroy()

	result, err := performRun(run)
	if err != nil {
		errorResponse(400, err, c)
		return
	}

	c.Header("X-Run-Command", req.Command)
	c.Header("X-Run-ExitCode", strconv.Itoa(result.ExitCode))
	c.Header("X-Run-Duration", result.Duration)

	c.Data(200, req.Format, result.Output)
}
Exemplo n.º 5
0
func IndexHandler(c *gin.Context) {

	var listTmpl = template.Must(template.ParseFiles("templates/base.html",
		"apps/message/templates/index.html"))

	User, _ := c.Get("User")
	Sid, _ := c.Get("Sid")
	sid := Sid.(string)
	//fmt.Println("User+++==>", Sid)

	bapi := auth.GetBackendApi2(c)
	data := gin.H{}
	if err := bapi.Get(&data, "http://127.0.0.1:8080/messages"); err != nil {
		fmt.Println("bapi failed:", err)
		return
	}

	if e, exist := data["error"]; exist {
		fmt.Println("get messages failed:", e.(string))
		if e.(string) == "session expired" {
			conn := utils.OpenDB()
			auth.Signout_del_session(conn, sid)
			c.Redirect(302, "/auth/signin")
			return
		}
		// TODO: else
	}

	data["User"] = User

	if err := listTmpl.Execute(c.Writer, data); err != nil {
		fmt.Println(err.Error())
	}

}
Exemplo n.º 6
0
// Hostname returns the hostname associated with
// the current context.
func Hostname(c *gin.Context) (host string) {
	v, ok := c.Get("host")
	if ok {
		host = v.(string)
	}
	return
}
Exemplo n.º 7
0
// IsTatSystem return true if user is a system user. Get value in gin.Context
func IsTatSystem(ctx *gin.Context) bool {
	value, exist := ctx.Get(TatCtxIsSystem)
	if value != nil && exist && value.(bool) == true {
		return true
	}
	return false
}
Exemplo n.º 8
0
// convertByURLHandler is the main v1 API handler for converting a HTML to a PDF
// via a GET request. It can either return a JSON string indicating that the
// output of the conversion has been uploaded or it can return the output of
// the conversion to the client (raw bytes).
func convertByURLHandler(c *gin.Context) {
	s := c.MustGet("statsd").(*statsd.Client)
	r, ravenOk := c.Get("sentry")

	url := c.Query("url")
	if url == "" {
		c.AbortWithError(http.StatusBadRequest, ErrURLInvalid).SetType(gin.ErrorTypePublic)
		s.Increment("invalid_url")
		return
	}

	ext := c.Query("ext")

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

	conversionHandler(c, *source)
}
Exemplo n.º 9
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)
}
Exemplo n.º 10
0
func ReadSeriesOfUserHandler(c *gin.Context, app AppContext) error {
	tmp, err := c.Get("Session")
	if err != nil {
		return err
	}

	s, ok := tmp.(aauth.Session)
	if !ok {
		errors.New("Cannot find session")
	}

	userID := c.Params.ByName("id")
	if s.UserID == userID {
		errors.New("Wrong user")
	}

	db := app.DB()
	defer db.Session.Close()
	sList, err := ReadSeriesOfUser(db, bson.ObjectIdHex(s.UserID))

	if err != nil {
		return err
	}

	resp := NewSuccessResponse(sList)
	c.JSON(http.StatusOK, resp)

	return nil
}
Exemplo n.º 11
0
func DB(ctx *gin.Context) *gorm.DB {
	newDB, exist := ctx.Get("DB")
	if exist {
		return newDB.(*gorm.DB)
	}
	return db.DB
}
Exemplo n.º 12
0
Arquivo: main.go Projeto: t2y/misc
func getDB(c *gin.Context) *sql.DB {
	db, ok := c.Get("DB")
	if ok {
		return db.(*sql.DB)
	}
	return nil
}
Exemplo n.º 13
0
func AuthCheck(c *gin.Context) {
	id, _ := c.Get("request_id")
	log.InfoFields("Checking auth token", log.Fields{
		"request_id": id,
	})

	token := c.Query("token")
	if token == "" {
		tokenHeaders := c.Request.Header["Token"]
		if len(tokenHeaders) == 0 {
			c.AbortWithError(http.StatusUnauthorized, fmt.Errorf("No notion access token provided"))
			return
		} else {
			token = tokenHeaders[0]
		}
	}

	in, user, err := db.GetUserByToken(token)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("Internal server error"))
		return
	}
	if !in {
		c.AbortWithError(http.StatusUnauthorized, fmt.Errorf("Notion access token provided is not currently valid"))
		return
	}

	c.Set("request_user_id", user.Id)
}
Exemplo n.º 14
0
func DeleteChirp(c *gin.Context) {
	var id = c.Params.ByName("id")
	var chirp model.Chirp

	uid, _ := c.Get("userid")
	userid, _ := Atoi(uid.(string))
	chirp.Id, _ = Atoi(id)

	row := util.DB.QueryRow(chirp.StmtGetById())
	err := row.Scan(&chirp.Id, &chirp.Userid, &chirp.Type, &chirp.Message, &chirp.Create_date, &chirp.Active)
	if err != nil {
		c.JSON(400, sys.JSON_NOACCESS)
		return
	}

	// Check if chirp belongs to requester's account
	if chirp.Userid != userid {
		c.JSON(403, sys.JSON_NOACCESS)
		return
	}

	row = util.DB.QueryRow(chirp.StmtSetActive(false))
	err = row.Scan(&chirp.Id)
	if err != nil {
		c.JSON(500, gin.H{"message": sys.ERR_DB_DELETE, "status": sys.FAIL, "payload": id})
		return
	}
	c.JSON(200, gin.H{"payload": "Deleted Chirp " + Itoa(chirp.Id), "status": sys.SUCCESS})

}
Exemplo n.º 15
0
func GetToken(c *gin.Context) *tokenModel {
	token, exists := c.Get("token")
	if !exists {
		panic("token not exists")
	}
	return token.(*tokenModel)
}
Exemplo n.º 16
0
func Current(c *gin.Context) (u *User, loggedIn bool) {
	intf, ok := c.Get(Ctx_LoggedInKey)
	if ok {
		loggedIn = intf.(bool)
	}
	if ok && !loggedIn {
		return
	}
	intf, ok = c.Get(Ctx_UserPtrKey)
	if ok && loggedIn {
		u = intf.(*User)
		return
	}

	sess := session.FromContext(c)
	uid, ok := sess.Uint(Sess_UserIdKey)
	if !ok {
		c.Set(Ctx_LoggedInKey, false)
		return nil, false
	}

	u, ok = Find(uid)
	if !ok {
		c.Set(Ctx_LoggedInKey, false)
		return nil, false
	}

	c.Set(Ctx_LoggedInKey, true)
	c.Set(Ctx_UserPtrKey, u)
	return u, true
}
Exemplo n.º 17
0
func Error(c *gin.Context) {
	c.Next()
	id, _ := c.Get("request_id")

	// Log out every error we have encoutered (which in most cases is just 1)
	for _, ginError := range c.Errors {
		actError := ginError.Err
		log.InfoFields("Request error", log.Fields{
			"request_id": id,
			"body":       formatErrorBody(actError.Error()),
		})
	}

	// Grab the last error and use that as the error we return to the client
	if len(c.Errors) > 0 {
		clientError := c.Errors[len(c.Errors)-1].Err

		// If it isn't an errors.Http type, assume it is a 500 and return that
		switch clientError.(type) {
		case errors.Http:
			break
		default:
			if c.IsAborted() {
				clientError = errors.NewHttp(c.Writer.Status(), formatErrorBody(clientError.Error()))
			} else {
				clientError = errors.NewHttp(http.StatusInternalServerError, "Unrecognized error")
			}
		}

		// Now write the error to the client
		c.JSON(clientError.(errors.Http).Code, clientError)
	}

}
Exemplo n.º 18
0
func saveCurrentChannelEndPoint(c *gin.Context) {
	var json = &struct {
		ID   int    `json:"ID"`
		Type string `json:"Type"`
	}{}

	if c.Bind(json) != nil {
		c.JSON(http.StatusBadRequest, gin.H{"ERR": "WRONG_INPUT"})
		return
	}

	userID64, _ := c.Get("userID")
	userID := userID64.(int)

	cc := &CurrentChannel{
		Type: json.Type,
		ID:   json.ID,
	}

	if peer, ok := peers.get(userID); ok {
		maxMsgId, _ := maxMsgIDofRoom(json.ID)
		cc.LastMsgID = maxMsgId
		peer.ccUpdate(cc)
	}

	if _, err := saveCurrentChannel(userID, cc); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"ERR": "INTERNAL_SERVER_ERROR",
		})
	} else {

		c.JSON(http.StatusOK, gin.H{"SUC": "OK"})
	}
}
Exemplo n.º 19
0
func GetChirpsByUser(c *gin.Context) {
	var arr []model.Chirp
	var chirp model.Chirp

	uid, _ := c.Get("userid")
	chirp.Id, _ = Atoi(uid.(string))

	log.Printf("... GetUser ... ")
	rows, err := util.DB.Query(chirp.StmtSelectByUserId())
	if err != nil {
		c.JSON(400, gin.H{"message": sys.ERR_DB_NO_MATCH, "status": sys.FAIL})
		return
	}

	//util.PanicIf(err)
	for rows.Next() {
		var cp model.Chirp
		if err := rows.Scan(&cp.Id, &cp.Type, &cp.Message, &cp.Create_date, &cp.Active); err != nil {
			c.JSON(400, gin.H{"message": sys.ERR_SCAN_ROW, "status": sys.FAIL})
			return
		} else {
			arr = append(arr, cp)
		}
	}

	c.JSON(200, arr)
}
Exemplo n.º 20
0
func createRoomEndPoint(c *gin.Context) {
	var json = &struct {
		Name        string `form:"name" 		json:"name" 		binding:"required"`
		Description string `form:"description" json:"description"`
	}{}

	if c.Bind(json) != nil {
		c.JSON(http.StatusBadRequest, gin.H{"ERR": "WRONG_INPUT"})
		return
	}

	userID64, _ := c.Get("userID")

	roomRaw := &RoomData{
		Name:        json.Name,
		Description: json.Description,
		OwnerID:     userID64.(int),
	}

	roomID, err := saveRoomRaw(roomRaw)

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"ERR": "INTERNAL_SERVER_ERR"})
		return
	}

	if peer, ok := peers.get(userID64.(int)); ok {
		peer.joinRoom(roomID)
	}

	// return roomid and name
	c.JSON(http.StatusOK, gin.H{
		"ID": roomID, "Name": json.Name,
	})
}
Exemplo n.º 21
0
func FromContext(c *gin.Context) *Session {
	if val, ok := c.Get("session"); ok {
		if s, ok := val.(*Session); ok {
			return s
		}
	}

	cookie, err := c.Request.Cookie(CookieKey)
	if err != nil {
		s := Create()
		s.storeInContext(c)
		http.SetCookie(c.Writer, s.cookie())
		return s
	}

	s, err := Load(cookie.Value)
	if err != nil {
		s := Create()
		s.storeInContext(c)
		http.SetCookie(c.Writer, s.cookie())
		return s
	}

	s.storeInContext(c)
	return s
}
Exemplo n.º 22
0
// Repos is a middleware function that attempts to cache the
// user's list of remote repositories (ie in GitHub) to minimize
// remote calls that might be expensive, slow or rate-limited.
func Repos(c *gin.Context) {
	var user, _ = c.Get("user")

	if user == nil {
		c.Next()
		return
	}

	// if the item already exists in the cache
	// we can continue the middleware chain and
	// exit afterwards.
	v := cache.GetRepos(c, user.(*model.User))
	if v != nil {
		c.Set("repos", v)
		c.Next()
		return
	}

	// otherwise, if the item isn't cached we execute
	// the middleware chain and then cache the permissions
	// after the request is processed.
	c.Next()

	repos, ok := c.Get("repos")
	if ok {
		cache.SetRepos(c,
			user.(*model.User),
			repos.([]*model.RepoLite),
		)
	}
}
Exemplo n.º 23
0
func GetFeed(c *gin.Context) {
	user := session.User(c)
	remote := remote.FromContext(c)
	var repos []*model.RepoLite

	// get the repository list from the cache
	reposv, ok := c.Get("repos")
	if ok {
		repos = reposv.([]*model.RepoLite)
	} else {
		var err error
		repos, err = remote.Repos(user)
		if err != nil {
			c.String(400, err.Error())
			return
		}
	}

	feed, err := store.GetUserFeed(c, repos)
	if err != nil {
		c.String(400, err.Error())
		return
	}
	c.JSON(200, feed)
}
Exemplo n.º 24
0
func GetRepos(c *gin.Context) {
	user := session.User(c)
	remote := remote.FromContext(c)
	var repos []*model.RepoLite

	// get the repository list from the cache
	reposv, ok := c.Get("repos")
	if ok {
		repos = reposv.([]*model.RepoLite)
	} else {
		var err error
		repos, err = remote.Repos(user)
		if err != nil {
			c.AbortWithStatus(http.StatusInternalServerError)
			return
		}
	}

	// for each repository in the remote system we get
	// the intersection of those repostiories in Drone
	repos_, err := store.GetRepoListOf(c, repos)
	if err != nil {
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}

	c.Set("repos", repos)
	c.IndentedJSON(http.StatusOK, repos_)
}
Exemplo n.º 25
0
// gin middleware handler
// call this on your groups that require authentication
func Use(ctx *gin.Context) {

	err := Check(ctx)

	if err == nil {

		loggedIn, _ := ctx.Get(Prefix + "loggedIn")

		if loggedIn == true {

			if Authorized != nil {
				Authorized(ctx)
			}

		} else {

			if Unauthorized != nil {
				Unauthorized(ctx)
			}

		}

	}

}
Exemplo n.º 26
0
func TestReposCache(t *testing.T) {

	g := goblin.Goblin(t)
	g.Describe("Repo List Cache", func() {

		var c *gin.Context
		g.BeforeEach(func() {
			c = new(gin.Context)
			cache.ToContext(c, cache.Default())
		})

		g.It("should skip when no user session", func() {
			Perms(c)

			_, ok := c.Get("perm")
			g.Assert(ok).IsFalse()
		})

		g.It("should get repos from cache", func() {
			c.Set("user", fakeUser)
			cache.SetRepos(c, fakeUser, fakeRepos)

			Repos(c)

			repos, ok := c.Get("repos")
			g.Assert(ok).IsTrue()
			g.Assert(repos).Equal(fakeRepos)
		})

	})
}
Exemplo n.º 27
0
func TestSetPerm(t *testing.T) {
	g := goblin.Goblin(t)
	g.Describe("SetPerm", func() {
		g.BeforeEach(func() {
			os.Unsetenv("PUBLIC_MODE")
		})
		g.It("Should set pull to false (private repo, user not logged in)", func() {
			c := gin.Context{}
			c.Set("repo", &model.Repo{
				IsPrivate: true,
			})
			SetPerm()(&c)
			v, ok := c.Get("perm")
			g.Assert(ok).IsTrue("perm was not set")
			p, ok := v.(*model.Perm)
			g.Assert(ok).IsTrue("perm was the wrong type")
			g.Assert(p.Pull).IsFalse("pull should be false")
		})
		g.It("Should set pull to true (private repo, user not logged in, public mode)", func() {
			os.Setenv("PUBLIC_MODE", "true")
			c := gin.Context{}
			c.Set("repo", &model.Repo{
				IsPrivate: true,
			})
			SetPerm()(&c)
			v, ok := c.Get("perm")
			g.Assert(ok).IsTrue("perm was not set")
			p, ok := v.(*model.Perm)
			g.Assert(ok).IsTrue("perm was the wrong type")
			g.Assert(p.Pull).IsTrue("pull should be true")
		})
	})
}
Exemplo n.º 28
0
func GetProfile(c *gin.Context) (*Profile, error) {
	user, exists := c.Get(KeyNamespace)
	if !exists {
		return nil, errors.New("GinPassportFacebook namespace key doesn't exist")
	}

	return user.(*Profile), nil
}
Exemplo n.º 29
0
Arquivo: td.go Projeto: highsoul/eshop
func GetMe(c *gin.Context) model.User {
	user := model.User{}
	me, exist := c.Get("me")
	if exist {
		user = me.(model.User)
	}
	return user
}
Exemplo n.º 30
0
func getUser(c *gin.Context) {
	if u, exists := c.Get("_user"); exists {
		c.JSON(200, u)
		return
	}

	c.JSON(200, c.MustGet("user"))
}